public Stream UpdateRegisteredApplication(RegisteredApplication registeredApplicationForm) { BaseBusinessService <RegisteredApplication> businessService = (BaseBusinessService <RegisteredApplication>)BusinessFactory.Create(Keywords.UpdateRegisteredApplication); OperationResult result = businessService.Update(registeredApplicationForm); return(result.ToJsonStream()); }
public async Task <RegisteredApplication> CreateRegisteredApplication(string appname, string appdescription) { string newCid = await RegisteredApplication.CreateClientId(appname); string newSecret = await RegisteredApplication.CreateClientSecret(appname); RegisteredApplication ra = new RegisteredApplication() { ApplicationDescription = appdescription, ApplicationName = appname, ClientId = newCid, ClientSecret = newSecret }; var x = await Applications.AddAsync(ra); try { await SaveChangesAsync(); return(ra); } catch (DbUpdateException dbue) { return(null); } catch (Exception e) { return(null); } }
private async Task _applyClientCredentialsToken(ApplyTokenResponseContext context) { if (!String.IsNullOrWhiteSpace(context.Response.AccessToken)) { var at = context.Response.AccessToken; string clientid = context.Request.ClientId; var ei = context.Response.ExpiresIn ?? 0; // Write this Client Access Token to the database, replacing any old one that may be in use. MockifyDbContext DatabaseContext = context.HttpContext.RequestServices.GetRequiredService <MockifyDbContext>(); RegisteredApplication ra = await DatabaseContext.Applications.Include(x => x.ClientCredentialToken).FirstOrDefaultAsync(x => x.ClientId == clientid); if (ra == null) { // ?? return; } else { ra.ClientCredentialToken = new UserApplicationToken() { ClientId = clientid, TokenType = "client_credential", TokenValue = at, ExpiresAt = DateTime.UtcNow.AddSeconds(ei) }; await DatabaseContext.SaveChangesAsync(); _stripUnnecessaryResponseParameters(context); } } }
public async Task Heartbeat_UpdateServiceSubscription() { // Arrange const uint ttl = 10000; A.CallTo(() => _compassEnvironment.GetSubscriptionTtl()).Returns(ttl); var serviceSubscription = new ServiceSubscription { ApplicationToken = Guid.NewGuid() }; var registeredApplication = new RegisteredApplication(); A.CallTo(() => _validateApplicationTokenService.ValidateApplicationTokenAsync(serviceSubscription.ApplicationToken)) .Returns(Task.FromResult(registeredApplication)); A.CallTo(() => _dataStore.GetServiceSubscriptionAsync(serviceSubscription.ApplicationToken)) .Returns(Task.FromResult(serviceSubscription)); // Act await _sut.Thump(serviceSubscription); // Assert A.CallTo(() => _dataStore.UpsertAsync(serviceSubscription, ttl)) .MustHaveHappened(Repeated.Exactly.Once); }
private void SendRegisteredApplicationToKafka(RegisteredApplication registeredApplication) { _kafkaProducerService.Produce(new CompassEvent { ApplicationToken = registeredApplication.ApplicationToken, DateCreated = DateTime.UtcNow, EventName = "ApplicationRegistered", Payload = new { registeredApplication.ApplicationName } }); }
public ActionResult AppEdit(RegisteredApplication app) { if (ModelState.IsValid) { app = new RegisteredApplicationManager().UpdateRegisteredApplication(app, UserID); return(RedirectToAction("Applications", "Profile")); } return(View(app)); }
public async Task <bool> CheckRedirectURIMatches(string redirectUri, string clientid) { if (String.IsNullOrWhiteSpace(redirectUri)) { return(false); } // Check is associated with the Client Id.... RegisteredApplication ra = await _mc.Applications.Include(x => x.RedirectURIs).FirstAsync(x => x.ClientId.Equals(clientid)); return(ra.RedirectURIs.Any(x => x.URI.Equals(redirectUri))); }
// ReSharper disable once UnusedParameter.Local private void Validate(RegisteredApplication registeredApplication, Guid applicationToken) { if (registeredApplication == null) { throw new RegisteredApplicationNotFoundException(applicationToken); } if (registeredApplication.IsRevoked) { throw new RevokedApplicationException(); } }
public async Task <bool> CheckSecretMatchesId(string clientId, string clientSecret) { RegisteredApplication ra = await _mc.Applications.Where(x => x.ClientId.Equals(clientId, StringComparison.Ordinal)).FirstAsync(); if (ra == null) { return(false); } // Note: to mitigate brute force attacks, you SHOULD strongly consider applying // a key derivation function like PBKDF2 to slow down the secret validation process. // You SHOULD also consider using a time-constant comparer to prevent timing attacks. return(ra.ClientSecret.Equals(clientSecret, StringComparison.Ordinal)); }
public OperationResult GetAuthenticationServer(string clientID) { IFindRegisteredApplicationRepository repo = (IFindRegisteredApplicationRepository)RepositoryFactory.Create("Find.Tools.OAuthServerManager.RegisteredApplication"); List <RegisteredApplication> applications = repo.FindByClientID(clientID); if (applications.Count > 0) { RegisteredApplication app = applications[0]; return(new OperationResult(true, app.AuthenticationUrl, app.AuthenticationUrl)); } return(new OperationResult(false, null)); }
public async Task <IActionResult> UpdateRegisteredApplication(RegisteredApplicationViewModel model, string returnUrl = "/applications") { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { RegisteredApplication registeredApp = await _context.Applications.Include(r => r.RedirectURIs).FirstOrDefaultAsync(r2 => r2.ClientId.Equals(model.ClientId)); if (registeredApp == null) { return(View()); // We failed? } var RedirectUriForm = HttpContext.Request.Form; List <string> rdis = registeredApp.RedirectURIs.Select(x => x.URI).ToList(); List <string> newRids = new List <string>(); foreach (string key in RedirectUriForm.Keys) { if (key.ToLowerInvariant().StartsWith("redirect_")) { string val = RedirectUriForm[key]; if (!String.IsNullOrWhiteSpace(val)) { bool success = Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out Uri testUri); if (success) { string pathAndQuery = testUri.ToString(); // Check that this item hasn't already been added if (!newRids.Contains(pathAndQuery)) { newRids.Add(pathAndQuery); } } } } } registeredApp.ApplicationDescription = String.IsNullOrEmpty(model.ApplicationDescription) ? registeredApp.ApplicationDescription : model.ApplicationDescription; registeredApp.ApplicationName = String.IsNullOrEmpty(model.ApplicationName) ? registeredApp.ApplicationName : model.ApplicationName; registeredApp.RedirectURIs = newRids.Any() ? newRids.Select((r) => { return(new RedirectURI(r) { RegisteredApplication = registeredApp, RegisteredApplicationId = registeredApp.ClientId }); }).ToList() : registeredApp.RedirectURIs; RegisteredApplication updated = await _context.UpdateRegisteredApplication(registeredApp); if (updated != null) { return(RedirectToLocal(returnUrl)); } } return(View()); }
public async Task <IActionResult> ChangeSecret(string clientId, string returnUrl = "/applications") { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { RegisteredApplication success = await _context.UpdateClientSecret(clientId); if (success != null) { return(RedirectToLocal($"/applications/{clientId}")); } } return(View()); }
public async Task <IActionResult> Register(RegisteredApplicationViewModel model, string returnUrl = "/applications") { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { RegisteredApplication ra = await _context.CreateRegisteredApplication(model.ApplicationName, model.ApplicationDescription); if (ra != null) { return(RedirectToLocal(returnUrl)); } } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Index(CancellationToken cancellationToken) { OpenIdConnectRequest request = HttpContext.GetOpenIdConnectRequest(); RegisteredApplication ra = await(from entity in _mockifyContext.Applications where entity.ClientId == request.ClientId select entity).SingleOrDefaultAsync(cancellationToken); if (ra == null) { return(View("Error", new AuthorizeErrorViewModel { Error = OpenIdConnectConstants.Errors.InvalidClient, ErrorDescription = "Details concerning the calling client " + "application cannot be found in the database" })); } /* Regular view */ List <SpotifyScope> sscopes = new List <SpotifyScope>() { SpotifyScope.Public }; if (!string.IsNullOrWhiteSpace(request.Scope)) { foreach (string split in request.Scope.Split(',')) { if (SpotifyScope.IdMap.ContainsKey(split)) { var scope = SpotifyScope.IdMap[split]; if (!sscopes.Contains(scope)) { sscopes.Add(SpotifyScope.IdMap[split]); /* no dupes */ } } } } return(View(new AuthorizeViewModel() { AppName = ra.ApplicationName, ClientId = ra.ClientId, Description = ra.ApplicationDescription, RedirectUri = request.RedirectUri, TokenType = request.ResponseType, Scopes = sscopes, State = request.State })); }
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { // Get the set of serializable members for our class and base classes Type thisType = obj.GetType(); MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context); System.Drawing.Image image = null; List <object> dataList = new List <object>(); SerializationInfoEnumerator sie = info.GetEnumerator(); while (sie.MoveNext()) { object val = sie.Current.Value; if (sie.Name == "icon") { image = val as System.Drawing.Image; val = null; } dataList.Add(val); } object[] data = dataList.ToArray(); obj = FormatterServices.PopulateObjectMembers(obj, mi, data); // handle the icon if (image != null) { RegisteredApplication ra = obj as RegisteredApplication; if (ra != null) { ra.IconID = ImageCache.Add(ra.Name, image); image.Dispose(); image = null; } else { RegisteredNotification rn = obj as RegisteredNotification; if (rn != null) { AddTemporaryNotificationImage(rn, image); // dont dispose of the image yet, it will get taken care of later } } } return(obj); }
public void Initialize(GlobalDiscoveryServer gds, PushConfigurationServer server, RegisteredApplication application, bool isHttps) { m_gds = gds; m_server = server; m_application = application; // display local trust list. if (application != null) { m_trustListStorePath = (isHttps) ? m_application.HttpsTrustListStorePath : m_application.TrustListStorePath; m_issuerListStorePath = (isHttps) ? m_application.HttpsIssuerListStorePath : m_application.IssuerListStorePath; CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null); MergeWithGdsButton.Enabled = !String.IsNullOrEmpty(m_trustListStorePath); } ApplyChangesButton.Enabled = false; }
public async Task <RegisteredApplication> UpdateRegisteredApplication(RegisteredApplication ra) { if (ra == null) { return(null); // No such element } try { await SaveChangesAsync(); return(ra); } catch (DbUpdateException dbue) { return(null); } catch (Exception e) { return(null); } }
public async Task Heartbeat_UpdateRegisteredApplication() { // Arrange var serviceSubscription = new ServiceSubscription { ApplicationToken = Guid.NewGuid() }; var registeredApplication = new RegisteredApplication(); A.CallTo(() => _validateApplicationTokenService.ValidateApplicationTokenAsync(serviceSubscription.ApplicationToken)) .Returns(Task.FromResult(registeredApplication)); // Act await _sut.Thump(serviceSubscription); // Assert A.CallTo(() => _dataStore.UpsertAsync(registeredApplication)) .MustHaveHappened(Repeated.Exactly.Once); }
public async Task RegisterNewApplication_ValidateUniqueAppName() { // Arrange var appName = "Rouge One"; var registeredApplication = new RegisteredApplication { ApplicationName = appName, ApplicationToken = Guid.NewGuid(), DateCreated = DateTime.Now }; A.CallTo(() => _dataStore.GetRegisteredApplicationAsync(appName)) .Returns(Task.FromResult(registeredApplication)); // Act async Task Action() => await _sut.RegisterNewApplicationAsync(appName); // Assert await Assert.ThrowsAsync <ApplicationAlreadyRegisteredException>(Action); }
private async void RegistrationPanel_RegisteredApplicationChangedAsync(object sender, RegisteredApplicationChangedEventArgs e) { try { var app = m_registeredApplication = e.Application; if (app == null || app.RegistrationType == RegistrationType.ClientPull) { SetServer(null); } else if (app.RegistrationType == RegistrationType.ServerPush) { if (!String.IsNullOrEmpty(app.ServerUrl)) { var endpoint = new EndpointDescription(app.ServerUrl); endpoint.Server.ApplicationType = ApplicationType.Server; endpoint.Server.ApplicationUri = app.ApplicationUri; endpoint.Server.ProductUri = app.ProductUri; endpoint.Server.ApplicationName = app.ApplicationName; endpoint.Server.DiscoveryUrls = (app.DiscoveryUrl != null) ? new StringCollection(app.DiscoveryUrl) : null; SetServer(endpoint); } } CertificateButton.Enabled = (e.Application != null); TrustListButton.Enabled = (e.Application != null); #if !NO_HTTPS HttpsCertificateButton.Visible = (e.Application != null && !String.IsNullOrEmpty(e.Application.GetHttpsDomainName())); HttpsTrustListButton.Visible = (e.Application != null && !String.IsNullOrEmpty(e.Application.HttpsTrustListStorePath)); #endif await CertificatePanel.Initialize(m_configuration, m_gds, m_server, e.Application, false); TrustListPanel.Initialize(m_gds, m_server, e.Application, false); } catch (Exception ex) { Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex); } }
public async Task <IActionResult> Index(string clientid) { RegisteredApplication ra = await _context.Applications.Include(r => r.RedirectURIs).FirstOrDefaultAsync(r2 => r2.ClientId.Equals(clientid)); if (ra == null) { return(Error()); } else { RegisteredApplicationViewModel rvm = new RegisteredApplicationViewModel() { ApplicationDescription = ra.ApplicationDescription, ApplicationName = ra.ApplicationName, RedirectURIs = ra.RedirectURIs.Select(x => x.URI), ClientId = ra.ClientId, ClientSecret = ra.ClientSecret }; return(View(rvm)); } }
public async Task Revoke_RevokeApplication() { // Arrange var appToken = Guid.NewGuid(); var serviceApplication = new RegisteredApplication() { ApplicationToken = appToken, IsRevoked = false }; A.CallTo(() => _dataStore.GetByDocumentIdAsync <RegisteredApplication>(A <string> ._)) .Returns(serviceApplication); // Act await _sut.RevokeApplicationAsync(appToken); // Assert A.CallTo(() => _dataStore.UpsertAsync(serviceApplication)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => _dataStore.UpsertAsync(A <RegisteredApplication> .That.Matches(arg => arg.IsRevoked))) .MustHaveHappened(Repeated.Exactly.Once); }
public ActionResult AppEdit(int?id) { var app = new RegisteredApplication(); var userId = (int)UserID; if (id != null) { using (var appManager = new RegisteredApplicationManager()) { app = appManager.GetRegisteredApplication((int)id, userId); } } else { app.UserID = userId; app.IsEnabled = true; app.IsWriteEnabled = true; } return(View("AppEdit", app)); }
public RegisteredApplication UpdateRegisteredApplication(RegisteredApplication update, int?userId) { Core.Data.RegisteredApplication item = new Core.Data.RegisteredApplication(); if (update.ID > 0) { item = dataModel.RegisteredApplications.FirstOrDefault(a => a.Id == update.ID && (userId == null || (userId != null && update.UserID == userId))); } else { item.DateCreated = DateTime.UtcNow; item.IsEnabled = true; item.PrimaryApikey = Guid.NewGuid().ToString().ToLower(); item.AppId = Guid.NewGuid().ToString().ToLower(); item.SharedSecret = Guid.NewGuid().ToString().ToLower(); item.UserId = (int)userId; } item.Title = update.Title; item.WebsiteUrl = update.WebsiteURL; item.Description = update.Description; item.IsPublicListing = update.IsPublicListing; if (userId == null) { item.IsEnabled = update.IsEnabled; item.IsWriteEnabled = update.IsWriteEnabled; } if (item.Id == 0) { dataModel.RegisteredApplications.Add(item); } dataModel.SaveChanges(); return(OCM.API.Common.Model.Extensions.RegisteredApplication.FromDataModel(item)); }
public async Task <RegisteredApplication> UpdateClientSecret(string clientid) { RegisteredApplication old = await Applications.FindAsync(clientid); if (old == null) { return(null); // No such entity } old.ClientSecret = await RegisteredApplication.CreateClientSecret(old.ApplicationName); Applications.Update(old); try { await SaveChangesAsync(); return(old); } catch (DbUpdateException dbue) { return(null); } catch (Exception e) { return(null); } }
public async Task <bool> DeleteRegisteredApplication(string clientId) { RegisteredApplication ra = await Applications.Include(x => x.RedirectURIs).FirstAsync(x => x.ClientId.Equals(clientId)); if (ra == null) { return(false); // No such element } else { Applications.Remove(ra); try { await SaveChangesAsync(); return(true); } catch (DbUpdateException dbue) { return(false); } catch (Exception e) { return(false); } } }
public async Task <IActionResult> Accept(CancellationToken cancellationToken) { ApplicationUser au = await _userManager.GetUserAsync(HttpContext.User); if (au == null) { return(View("Error", new AuthorizeErrorViewModel() { Error = "No such user", ErrorDescription = "Failed to find specified user" })); } OpenIdConnectRequest request = HttpContext.GetOpenIdConnectRequest(); ClaimsIdentity identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme, OpenIdConnectConstants.Claims.Name, OpenIdConnectConstants.Claims.Role); // We serialize the user_id so we can determine which user the caller of this token is string userid = _userManager.GetUserId(HttpContext.User); identity.AddClaim( new Claim(OpenIdConnectConstants.Claims.Subject, userid) .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken)); // We serialize the grant_type so we can user discriminate rate-limits. AuthorizationCode grants have the highest rate-limit allowance identity.AddClaim( new Claim("grant_type", OpenIdConnectConstants.GrantTypes.AuthorizationCode) .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken)); // We serialize the client_id so we can monitor for usage patterns of a given app, and also to allow for app-based token revokes. identity.AddClaim( new Claim("client_id", request.ClientId) .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken)); RegisteredApplication ra = await(from entity in _mockifyContext.Applications where entity.ClientId == request.ClientId select entity).SingleOrDefaultAsync(cancellationToken); if (ra == null) { return(View("Error", new AuthorizeErrorViewModel { Error = OpenIdConnectConstants.Errors.InvalidClient, ErrorDescription = "Details concerning the calling client " + "application cannot be found in the database" })); } AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), new AuthenticationProperties(), OpenIdConnectServerDefaults.AuthenticationScheme); List <string> scopesToAdd = new List <string>() { OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.OfflineAccess, SpotifyScope.Public.Name, }; if (!String.IsNullOrWhiteSpace(request.Scope)) { foreach (string scope in request.Scope.Split(',')) { if (SpotifyScope.IdMap.ContainsKey(scope) && !scopesToAdd.Contains(scope)) { scopesToAdd.Add(scope); } } } ticket.SetScopes(scopesToAdd); ticket.SetResources("resource_server"); // ?? what is this Microsoft.AspNetCore.Mvc.SignInResult sr = SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); return(sr); }
public async Task Initialize( GlobalDiscoveryClientConfiguration configuration, GlobalDiscoveryServerMethods gds, ServerPushConfigurationMethods server, RegisteredApplication application, bool isHttps) { m_configuration = configuration; m_gds = gds; m_server = server; m_application = application; m_certificate = null; m_certificatePassword = null; CertificateRequestTimer.Enabled = false; RequestProgressLabel.Visible = false; ApplyChangesButton.Enabled = false; CertificateControl.ShowNothing(); X509Certificate2 certificate = null; if (!isHttps) { if (server.Endpoint != null && server.Endpoint.Description.ServerCertificate != null) { certificate = new X509Certificate2(server.Endpoint.Description.ServerCertificate); } else if (application != null) { if (!String.IsNullOrEmpty(application.CertificatePublicKeyPath)) { string file = Utils.GetAbsoluteFilePath(application.CertificatePublicKeyPath, true, false, false); if (file != null) { certificate = new X509Certificate2(file); } } else if (!String.IsNullOrEmpty(application.CertificateStorePath)) { CertificateIdentifier id = new CertificateIdentifier { StorePath = application.CertificateStorePath }; id.StoreType = CertificateStoreIdentifier.DetermineStoreType(id.StorePath); id.SubjectName = application.CertificateSubjectName.Replace("localhost", Utils.GetHostName()); certificate = await id.Find(true); } } } else { if (application != null) { if (!String.IsNullOrEmpty(application.HttpsCertificatePublicKeyPath)) { string file = Utils.GetAbsoluteFilePath(application.HttpsCertificatePublicKeyPath, true, false, false); if (file != null) { certificate = new X509Certificate2(file); } } else { foreach (string disoveryUrl in application.DiscoveryUrl) { if (Uri.IsWellFormedUriString(disoveryUrl, UriKind.Absolute)) { Uri url = new Uri(disoveryUrl); CertificateIdentifier id = new CertificateIdentifier() { StoreType = CertificateStoreType.X509Store, StorePath = "CurrentUser\\UA_MachineDefault", SubjectName = "CN=" + url.DnsSafeHost }; certificate = await id.Find(); } } } } } if (certificate != null) { try { CertificateControl.Tag = certificate.Thumbprint; } catch (Exception) { MessageBox.Show( Parent, "The certificate does not appear to be valid. Please check configuration settings.", Parent.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); certificate = null; } } WarningLabel.Visible = certificate == null; if (certificate != null) { m_certificate = certificate; CertificateControl.ShowValue(null, "Application Certificate", new CertificateWrapper() { Certificate = certificate }, true); } }
private async Task UpdateLastSeenAsync(RegisteredApplication registeredApplication) { registeredApplication.LastSeen = DateTime.UtcNow; await _dataStore.UpsertAsync(registeredApplication); }
public async Task <ErrorOrNot> CheckToken() { if (HttpContext.Request.Headers.TryGetValue("Authorization", out Microsoft.Extensions.Primitives.StringValues auth)) { if (!auth.Any()) { return(new ErrorOrNot(SendError(401, "No token provided"))); } string authStr = auth.ToString(); string[] splits = authStr.Split(' '); if (splits.Length != 2 || splits[0] != "Bearer") { return(new ErrorOrNot(SendError(400, "Only valid bearer authentication supported"))); } string access = splits[1]; ApplicationUser au = await _mc.Users.Include(x => x.UserApplicationTokens).Include(x => x.OverallRateLimit).Where(x => x.UserApplicationTokens.Any(y => y.TokenValue == access)).FirstOrDefaultAsync(); if (au == null) { return(new ErrorOrNot(SendError(401, "Invalid access token"))); } UserApplicationToken uat = au.UserApplicationTokens.Where(x => x.TokenValue == access).FirstOrDefault(); if (uat == null) { return(new ErrorOrNot(SendError(401, "Invalid access token"))); } if (uat.IsExpired) { return(new ErrorOrNot(SendError(401, "The access token expired"))); } RegisteredApplication ra = await _mc.Applications.Include(x => x.OverallRateLimit).Where(x => x.ClientId == uat.ClientId).FirstOrDefaultAsync(); if (ra == null) { return(new ErrorOrNot(SendError(404, "Application does not exist"))); // TODO figure out what error Spotify sends when using a no longer valid client-id token } /* Check that Server isn't in Rate Limit Mode */ if (_serverSettings.RateLimits.IsRateLimited) { return(new ErrorOrNot(SendRateLimit(_serverSettings.RateLimits))); } // TODO check that Endpoint isn't in Rate Limit Mode /* Check that Application isn't in Rate Limit Mode */ if (ra.OverallRateLimit.IsRateLimited) { return(new ErrorOrNot(SendRateLimit(ra.OverallRateLimit))); } /* Check that User isn't in Rate Limit Mode */ if (au.OverallRateLimit.IsRateLimited) { return(new ErrorOrNot(SendRateLimit(au.OverallRateLimit))); } // TODO check that user is within App Rate Limit if (uat.AppUserRateLimits.IsRateLimited) { return(new ErrorOrNot(SendRateLimit(uat.AppUserRateLimits))); } /* Finally, if successful, increment api call count */ _serverSettings.RateLimits.CurrentCalls += 1; // TODO increment Endpoint rate limit ra.OverallRateLimit.CurrentCalls += 1; au.OverallRateLimit.CurrentCalls += 1; uat.AppUserRateLimits.CurrentCalls += 1; _mc.SaveChangesAsync(); // No need to await. return(new ErrorOrNot()); // Success } return(new ErrorOrNot(SendError(401, "No token provided"))); }