コード例 #1
0
 internal MorphologicalAnalysisService(ApiKeyService apiKeyService, SentenceService sentenceService, IHttpClientFactory httpClientFactory, MorphemeFieldService morphemeFieldService)
 {
     this.apiKeyService        = apiKeyService;
     this.sentenceService      = sentenceService;
     IHttpClientFactory        = httpClientFactory;
     this.morphemeFieldService = morphemeFieldService;
 }
コード例 #2
0
ファイル: ApiKeyServiceUT.cs プロジェクト: cf2080/SSO
        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();
            }
        }
コード例 #3
0
ファイル: ApiKeyServiceUT.cs プロジェクト: cf2080/SSO
        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);
            }
        }
コード例 #4
0
ファイル: ApiKeyServiceUT.cs プロジェクト: cf2080/SSO
        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();
            }
        }
コード例 #5
0
        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);
        }
コード例 #7
0
        public void GetApiSecretTests(ApiType apiType)
        {
            ApiKeyService apiKeyService = new ApiKeyService(_configuration);

            string key = apiKeyService.GetApiSecret(apiType);

            Assert.False(string.IsNullOrEmpty(key));
        }
コード例 #8
0
 public ApplicationManager(DatabaseContext _db)
 {
     this._db            = _db;
     _applicationService = new ApplicationService(_db);
     _apiKeyService      = new ApiKeyService(_db);
     _emailService       = new EmailService();
     _tokenService       = new TokenService();
 }
コード例 #9
0
        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));
        }
コード例 #10
0
        public void CreateKey_Fail_NullValuesShouldReturnNull()
        {
            using (_db = tu.CreateDataBaseContext())
            {
                // Act
                var result = ApiKeyService.CreateKey(_db, null);

                // Assert
                Assert.IsNull(result);
            }
        }
コード例 #11
0
 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));
     }
 }
コード例 #12
0
 public HttpResponseMessage Delete(HttpRequestMessage request, int id)
 {
     try
     {
         ApiKeyService.Delete(id);
         return(new HttpResponseMessage(HttpStatusCode.OK));
     }
     catch (Exception)
     {
         return(new HttpResponseMessage(HttpStatusCode.BadRequest));
     }
 }
コード例 #13
0
        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)));
        }
コード例 #14
0
ファイル: ApiKeyServiceUT.cs プロジェクト: cf2080/SSO
        public void GetApiKeyByKey_Fail_NullValuesShouldReturnNull()
        {
            using (_db = tu.CreateDataBaseContext())
            {
                IApiKeyService _apiKeyService = new ApiKeyService(_db);

                // Act
                var result = _apiKeyService.GetKey(null);

                // Assert
                Assert.IsNull(result);
            }
        }
コード例 #15
0
        /// <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;
        }
コード例 #16
0
        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);
            }
        }
コード例 #17
0
        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);
            }
        }
コード例 #18
0
        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>()));
        }
コード例 #19
0
        // 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();
        }
コード例 #20
0
        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>()));
        }
コード例 #21
0
ファイル: ApiKeyServiceUT.cs プロジェクト: cf2080/SSO
        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);
            }
        }
コード例 #22
0
        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>()));
        }
コード例 #23
0
        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>()));
        }
コード例 #24
0
        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>()));
        }
コード例 #25
0
        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);
        }
コード例 #26
0
        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);
            }
        }
コード例 #27
0
        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();
            }
        }
コード例 #28
0
        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);
        }
コード例 #29
0
        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();
            }
        }
コード例 #30
0
        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));
            }
        }