internal MorphologicalAnalysisService(ApiKeyService apiKeyService, SentenceService sentenceService, IHttpClientFactory httpClientFactory, MorphemeFieldService morphemeFieldService) { this.apiKeyService = apiKeyService; this.sentenceService = sentenceService; IHttpClientFactory = httpClientFactory; this.morphemeFieldService = morphemeFieldService; }
public void UpdateKey_Pass_ReturnKey() { // Arrange newKey = tu.CreateApiKeyObject(); var expected = newKey.Key; // Act using (_db = tu.CreateDataBaseContext()) { IApiKeyService _apiKeyService = new ApiKeyService(_db); newKey = _apiKeyService.CreateKey(newKey); _db.SaveChanges(); newKey.Key = "A new Key"; var response = _apiKeyService.UpdateKey(newKey); _db.SaveChanges(); var result = _db.Keys.Find(newKey.Id); // Assert Assert.IsNotNull(response); Assert.IsNotNull(result); Assert.AreEqual(result.Id, newKey.Id); Assert.AreNotEqual(expected, result.Key); _apiKeyService.DeleteKey(newKey.Id); _db.SaveChanges(); } }
public void UpdateKey_Fail_NonExistingKeyShouldThrowException() { // Arrange newKey = tu.CreateApiKeyObject(); var expected = newKey; // Act using (_db = tu.CreateDataBaseContext()) { IApiKeyService _apiKeyService = new ApiKeyService(_db); var response = _apiKeyService.UpdateKey(newKey); try { _db.SaveChanges(); } catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException) { _db.Entry(newKey).State = System.Data.Entity.EntityState.Detached; } catch (System.Data.Entity.Core.EntityCommandExecutionException) { _db.Entry(newKey).State = System.Data.Entity.EntityState.Detached; } var result = _db.Keys.Find(expected.Id); // Assert Assert.IsNull(response); Assert.IsNull(result); } }
public void CreateKey_Fail_ExistingKeyShouldReturnNull() { // Arrange newKey = tu.CreateApiKeyObject(); var expected = newKey; using (_db = tu.CreateDataBaseContext()) { IApiKeyService _apiKeyService = new ApiKeyService(_db); IApplicationService _applicationService = new ApplicationService(_db); // Act var response = _apiKeyService.CreateKey(newKey); _db.SaveChanges(); var actual = _apiKeyService.CreateKey(newKey); // Assert Assert.AreNotEqual(expected, actual); Assert.IsNotNull(response); Assert.IsNull(actual); _applicationService.DeleteApplication(newKey.ApplicationId); _db.SaveChanges(); } }
public IActionResult GetApiKeys([FromQuery] int page = 1, [FromQuery] int elementsPerPage = 10) { IEnumerable <ApiKey> keys = ApiKeyService.GetAllApiKeys(); IEnumerable <ApiKey> paginatedKeys = keys.Skip((page - 1) * elementsPerPage).Take(elementsPerPage); return(Ok(new PaginatedResponse(paginatedKeys.Select(k => new ApiKeyResponse(k)), keys.Count()))); }
public override void OnAuthorization(HttpActionContext actionContext) { var keyData = GetAuthParamsFromRequest(actionContext.Request); if (keyData == null) { AuthParamsNotFound(actionContext); return; } // Constructing svc as local var. If we make it a class instance var it will be cached in // this attribute and become a singleton, which means the dbcontext connection and its // cache will live on too. In real code you might do some service location IOC stuff here. var apiKeySvc = new ApiKeyService(new ApplicationDbContext()); var apiKey = apiKeySvc.GetById(keyData.ApiKey, keyData.OwnerId); if (apiKey == null) { ApiKeyNotFoundOrNotAuthorized(actionContext); return; } if (apiKey.HasAnyPermission(_permissions) == false) { ApiKeyNotFoundOrNotAuthorized(actionContext); return; } base.OnAuthorization(actionContext); }
public void GetApiSecretTests(ApiType apiType) { ApiKeyService apiKeyService = new ApiKeyService(_configuration); string key = apiKeyService.GetApiSecret(apiType); Assert.False(string.IsNullOrEmpty(key)); }
public ApplicationManager(DatabaseContext _db) { this._db = _db; _applicationService = new ApplicationService(_db); _apiKeyService = new ApiKeyService(_db); _emailService = new EmailService(); _tokenService = new TokenService(); }
public HttpResponseMessage Get(HttpRequestMessage request, int id) { var apiKey = ApiKeyService.FindOne(id); if (apiKey == null) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } return(request.CreateResponse(HttpStatusCode.OK, apiKey)); }
public void CreateKey_Fail_NullValuesShouldReturnNull() { using (_db = tu.CreateDataBaseContext()) { // Act var result = ApiKeyService.CreateKey(_db, null); // Assert Assert.IsNull(result); } }
public HttpResponseMessage Put(HttpRequestMessage request, ApiKeyDto dto) { try { var updatedApiKey = ApiKeyService.Update(dto); return(request.CreateResponse(HttpStatusCode.OK, updatedApiKey)); } catch (Exception) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } }
public HttpResponseMessage Delete(HttpRequestMessage request, int id) { try { ApiKeyService.Delete(id); return(new HttpResponseMessage(HttpStatusCode.OK)); } catch (Exception) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } }
public IActionResult CreateApiKey([FromBody] ApiKeyCreationRequest apiKeyCreationRequest) { if (apiKeyCreationRequest == null || string.IsNullOrWhiteSpace(apiKeyCreationRequest.Name)) { return(HandleBadRequest("A valid key name has to be supplied.")); } ApiKey key = ApiKeyService.CreateApiKey(apiKeyCreationRequest.Name); return(Created(GetNewResourceUri(key.Id), new ApiKeyResponse(key))); }
public void GetApiKeyByKey_Fail_NullValuesShouldReturnNull() { using (_db = tu.CreateDataBaseContext()) { IApiKeyService _apiKeyService = new ApiKeyService(_db); // Act var result = _apiKeyService.GetKey(null); // Assert Assert.IsNull(result); } }
/// <summary> /// This is the main class for this app. This function is the first function /// called and it setups the app analytic (If in release mode), components, /// requested theme and event handlers. /// </summary> public App() { // Init XAML Resources InitializeComponent(); // We want to use the controler if on xbox if (DeviceHelper.IsXbox) { RequiresPointerMode = ApplicationRequiresPointerMode.WhenRequested; } // Check that we are not using the default theme, // if not change the requested theme to the users // picked theme. if (!SettingsService.Instance.IsDefaultTheme) { RequestedTheme = SettingsService.Instance.ThemeType; } // Registor the dialogs NavigationService.Current.RegisterTypeAsDialog <CrashDialog>(); NavigationService.Current.RegisterTypeAsDialog <FilterDialog>(); NavigationService.Current.RegisterTypeAsDialog <PendingUpdateDialog>(); NavigationService.Current.RegisterTypeAsDialog <PinTileDialog>(); NavigationService.Current.RegisterTypeAsDialog <PlaylistDialog>(); NavigationService.Current.RegisterTypeAsDialog <ShareDialog>(); // Init Keys ApiKeyService.Init(); // Handle App Crashes CrashHelper.HandleAppCrashes(Current); // Enter and Leaving background handlers EnteredBackground += AppEnteredBackground; LeavingBackground += AppLeavingBackground; // During the transition from foreground to background the // memory limit allowed for the application changes. The application // has a short time to respond by bringing its memory usage // under the new limit. MemoryManager.AppMemoryUsageLimitChanging += MemoryManager_AppMemoryUsageLimitChanging; // After an application is backgrounded it is expected to stay // under a memory target to maintain priority to keep running. // Subscribe to the event that informs the app of this change. MemoryManager.AppMemoryUsageIncreased += MemoryManager_AppMemoryUsageIncreased; }
public void GetApiKeyByAppIdIsUsed_Fail_NonExistingKeyShouldReturnNull() { // Arrange Guid id = Guid.NewGuid(); ApiKey expected = null; // Act using (_db = tu.CreateDataBaseContext()) { var result = ApiKeyService.GetKey(_db, id, false); // Assert Assert.IsNull(result); Assert.AreEqual(expected, result); } }
public void GetApiKeyByKey_Fail_NonExistingKeyShouldReturnNull() { // Arrange string nonExistingKey = "key"; ApiKey expected = null; // Act using (_db = tu.CreateDataBaseContext()) { var result = ApiKeyService.GetKey(_db, nonExistingKey); // Assert Assert.IsNull(result); Assert.AreEqual(expected, result); } }
public async void Get_null_record() { var mock = new ServiceMockFacade <IApiKeyRepository>(); mock.RepositoryMock.Setup(x => x.Get(It.IsAny <string>())).Returns(Task.FromResult <ApiKey>(null)); var service = new ApiKeyService(mock.LoggerMock.Object, mock.RepositoryMock.Object, mock.ModelValidatorMockFactory.ApiKeyModelValidatorMock.Object, mock.BOLMapperMockFactory.BOLApiKeyMapperMock, mock.DALMapperMockFactory.DALApiKeyMapperMock); ApiApiKeyResponseModel response = await service.Get(default(string)); response.Should().BeNull(); mock.RepositoryMock.Verify(x => x.Get(It.IsAny <string>())); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ApiKeyService keyService; if (HostingEnvironment.IsDevelopment()) { keyService = new ApiKeyService(Configuration["SteamAchievementTracker:ApiKey"]); } else { keyService = new ApiKeyService(); } services.AddSingleton <IApiKeyService>(keyService); services.AddControllersWithViews(); }
public async void ByApiKeyHashed_Exists() { var mock = new ServiceMockFacade <IApiKeyRepository>(); var record = new ApiKey(); mock.RepositoryMock.Setup(x => x.ByApiKeyHashed(It.IsAny <string>())).Returns(Task.FromResult(record)); var service = new ApiKeyService(mock.LoggerMock.Object, mock.RepositoryMock.Object, mock.ModelValidatorMockFactory.ApiKeyModelValidatorMock.Object, mock.BOLMapperMockFactory.BOLApiKeyMapperMock, mock.DALMapperMockFactory.DALApiKeyMapperMock); ApiApiKeyResponseModel response = await service.ByApiKeyHashed(default(string)); response.Should().NotBeNull(); mock.RepositoryMock.Verify(x => x.ByApiKeyHashed(It.IsAny <string>())); }
public void GetApiKeyById_Fail_NonExistingKeyShouldReturnNull() { // Arrange Guid nonExistingKey = Guid.NewGuid(); ApiKey expected = null; // Act using (_db = tu.CreateDataBaseContext()) { IApiKeyService _apiKeyService = new ApiKeyService(_db); var result = _apiKeyService.GetKey(nonExistingKey); // Assert Assert.IsNull(result); Assert.AreEqual(expected, result); } }
public async void Delete() { var mock = new ServiceMockFacade <IApiKeyRepository>(); var model = new ApiApiKeyRequestModel(); mock.RepositoryMock.Setup(x => x.Delete(It.IsAny <string>())).Returns(Task.CompletedTask); var service = new ApiKeyService(mock.LoggerMock.Object, mock.RepositoryMock.Object, mock.ModelValidatorMockFactory.ApiKeyModelValidatorMock.Object, mock.BOLMapperMockFactory.BOLApiKeyMapperMock, mock.DALMapperMockFactory.DALApiKeyMapperMock); ActionResponse response = await service.Delete(default(string)); response.Should().NotBeNull(); mock.RepositoryMock.Verify(x => x.Delete(It.IsAny <string>())); mock.ModelValidatorMockFactory.ApiKeyModelValidatorMock.Verify(x => x.ValidateDeleteAsync(It.IsAny <string>())); }
public async void All() { var mock = new ServiceMockFacade <IApiKeyRepository>(); var records = new List <ApiKey>(); records.Add(new ApiKey()); mock.RepositoryMock.Setup(x => x.All(It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(records)); var service = new ApiKeyService(mock.LoggerMock.Object, mock.RepositoryMock.Object, mock.ModelValidatorMockFactory.ApiKeyModelValidatorMock.Object, mock.BOLMapperMockFactory.BOLApiKeyMapperMock, mock.DALMapperMockFactory.DALApiKeyMapperMock); List <ApiApiKeyResponseModel> response = await service.All(); response.Should().HaveCount(1); mock.RepositoryMock.Verify(x => x.All(It.IsAny <int>(), It.IsAny <int>())); }
public async void Create() { var mock = new ServiceMockFacade <IApiKeyRepository>(); var model = new ApiApiKeyRequestModel(); mock.RepositoryMock.Setup(x => x.Create(It.IsAny <ApiKey>())).Returns(Task.FromResult(new ApiKey())); var service = new ApiKeyService(mock.LoggerMock.Object, mock.RepositoryMock.Object, mock.ModelValidatorMockFactory.ApiKeyModelValidatorMock.Object, mock.BOLMapperMockFactory.BOLApiKeyMapperMock, mock.DALMapperMockFactory.DALApiKeyMapperMock); CreateResponse <ApiApiKeyResponseModel> response = await service.Create(model); response.Should().NotBeNull(); mock.ModelValidatorMockFactory.ApiKeyModelValidatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiApiKeyRequestModel>())); mock.RepositoryMock.Verify(x => x.Create(It.IsAny <ApiKey>())); }
public override void OnActionExecuting(HttpActionContext filterContext) { // Get API key provider var provider = new ApiKeyService(); var msgUnauthorized = new { Message = "Authorization required" }; var reqOptions = filterContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value); var keyValue = ""; if (!Config.AuthorizationRequired) { keyValue = "None"; } else if (filterContext.Request.Headers.Contains(ApiKey)) { keyValue = filterContext.Request.Headers.GetValues(ApiKey).First(); } else if (reqOptions.ContainsKey(ApiKey)) { keyValue = reqOptions[ApiKey]; } // Validate Token if (string.IsNullOrEmpty(keyValue) || !provider.ValidateKey(keyValue)) { filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized, msgUnauthorized); filterContext.Response.ReasonPhrase = "Unauthorized"; } else { var controller = filterContext.ControllerContext.Controller; var controllerUser = controller.GetType().GetProperty("CurrentUser"); if (controllerUser != null) { var user = provider.ApiKey.User; controllerUser.SetValue(controller, user); } } base.OnActionExecuting(filterContext); }
public void DeleteKey_Fail_NonExistingKeyShouldReturnNull() { // Arrange Guid nonExistingId = Guid.NewGuid(); var expected = nonExistingId; using (_db = new DatabaseContext()) { // Act var response = ApiKeyService.DeleteKey(_db, nonExistingId); _db.SaveChanges(); var result = _db.Keys.Find(expected); // Assert Assert.IsNull(response); Assert.IsNull(result); } }
public void CreateKey_Pass_ReturnKey() { // Arrange newKey = tu.CreateApiKeyObject(); var expected = newKey; using (_db = tu.CreateDataBaseContext()) { // Act var response = ApiKeyService.CreateKey(_db, newKey); _db.SaveChanges(); // Assert Assert.IsNotNull(response); Assert.AreEqual(response.Id, expected.Id); ApiKeyService.DeleteKey(_db, newKey.Id); _db.SaveChanges(); } }
public override void OnAuthorization(HttpActionContext actionContext) { var accessKey = FetchFromHeader(actionContext); if (accessKey == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } var apiKey = ApiKeyService.FindByAccessKey(accessKey); if (apiKey == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } if (!apiKey.isActive) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } if (AdminRestricted && !apiKey.isAdmin) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } var identity = new ClaimsIdentity(new List <Claim> { new Claim(ClaimTypes.Sid, "" + apiKey.Id), new Claim(ClaimTypes.UserData, apiKey.isAdmin ? "Admin" : "User") }); IPrincipal user = new ClaimsPrincipal(identity); actionContext.RequestContext.Principal = user; base.OnAuthorization(actionContext); }
public void GetApiKeyByAppIdIsUsed_Pass_ReturnKey() { // Arrange newKey = tu.CreateApiKeyObject(); var expected = newKey; // Act using (_db = tu.CreateDataBaseContext()) { newKey = ApiKeyService.CreateKey(_db, newKey); _db.SaveChanges(); var result = ApiKeyService.GetKey(_db, newKey.ApplicationId, false); // Assert Assert.IsNotNull(result); Assert.AreEqual(expected.Key, result.Key); ApiKeyService.DeleteKey(_db, newKey.Id); _db.SaveChanges(); } }
public IActionResult UpdateApiKeyStatus(Guid id, [FromBody] ApiKeyStatusUpdateRequest apiKeyStatusUpdateRequest) { if (apiKeyStatusUpdateRequest == null) { return(HandleBadRequest("Missing status data.")); } // Attempt to update status try { ApiKeyService.UpdateApiKeyStatus(id, apiKeyStatusUpdateRequest.Enabled); return(NoContent()); } catch (ApiKeyNotFoundException exception) { return(HandleResourceNotFoundException(exception)); } catch (Exception exception) { return(HandleUnexpectedException(exception)); } }