public async Task CreateAsync_ReturnSuccess_And_CreateNotBlockedUserInDb_When_PassingClientWithUri() { await this.InsertDefaultClient(1); await this.InsertDefaultClient(2); await this.InsertDefaultClient(3); var repository = new SqlCeClientRepository(this.ConnectionFactory); RepositoryResponse response = await repository.CreateAsync(new NewIdSrvClientDto { Name = "n", Secret = "s", Uri = "u" }); Assert.AreEqual(RepositoryResponse.Success, response); using (IDbConnection connection = await this.ConnectionFactory.GetConnectionAsync()) { var compiler = new SqlServerCompiler(); var db = new QueryFactory(connection, compiler); this.ConnectionFactory = new SqlCeConnectionFactory(this.TestConnectionString); IEnumerable <IdSrvClientDto> clients = await db.Query("Clients").GetAsync <IdSrvClientDto>(); Assert.AreEqual(4, clients.Count()); IdSrvClientDto createdClient = clients.Where(c => c.Name == "n").FirstOrDefault(); Assert.IsNotNull(createdClient); Assert.AreEqual("n", createdClient.Name); Assert.AreEqual("s", createdClient.Secret); Assert.AreEqual("u", createdClient.Uri); Assert.IsFalse(createdClient.IsBlocked); } }
public async Task Update_ReturnSelf_With_ClientReturnedFromRepo_OfType_UpdateIdSrvClientDTO_When_PassingClientId() { var clientId = Guid.NewGuid(); var client = new IdSrvClientDto() { Id = Guid.NewGuid(), Name = "n", Secret = "s", Uri = "u" }; this.ClientServiceMock .Setup(v => v.GetClientByIdAsync(clientId)) .ReturnsAsync(client); var controller = new ClientsController(this.ClientServiceMock.Object); ActionResult result = await controller.Update(clientId); Assert.IsInstanceOf <ViewResult>(result); var viewResult = result as ViewResult; Assert.NotNull(viewResult); Assert.AreEqual(string.Empty, viewResult.ViewName); Assert.IsInstanceOf <UpdateIdSrvClientDto>(controller.ViewData.Model); var model = controller.ViewData.Model as UpdateIdSrvClientDto; Assert.AreEqual(client.Id, model.Id); Assert.AreEqual(client.Name, model.Name); Assert.AreEqual(client.Secret, model.Secret); Assert.AreEqual(client.Uri, model.Uri); }
/// <inheritdoc/> public async Task <CustomGrantValidationResult> ValidateAsync(ValidatedTokenRequest request) { string userName = request.Raw.Get("name"); IdSrvUserDto user = await this.UserRepository.GetUserByUserNameAsync(userName); IdSrvClientDto client = await this.ClientRepository.GetClientByIdAsync(request.Client.ClientId); string password = request.Raw.Get("password"); // Выполняем проверку учетки пользователя // Значение ContextType.Machine для домена вероятно надо будет поменять на ContextType.Domain (не тестировал) var pc = new PrincipalContext(ContextType.Machine); bool isCredentialValid = false; if (user != null && !user.IsBlocked && client != null && !client.IsBlocked) { isCredentialValid = pc.ValidateCredentials(userName, password); } var authResult = new AuthenticateResult( subject: user != null ? user.Id.ToString() : "-", name: userName); var grantResult = new CustomGrantValidationResult { IsError = !isCredentialValid, Error = authResult.ErrorMessage, ErrorDescription = (user != null && user.IsBlocked) ? $"User \"{userName}\" is blocked" : authResult.ErrorMessage, Principal = authResult.User, }; return(grantResult); }
public async Task GetByNameAsync_ReturnNull_When_DbNotContainAnyClients() { var repository = new SqlCeClientRepository(this.ConnectionFactory); IdSrvClientDto client = await repository.GetByNameAsync("n2"); Assert.IsNull(client); }
public async Task <IHttpActionResult> GetByName(string name) { if (name == null) { return(this.BadRequest()); } IdSrvClientDto client = await this.ClientRepository.GetByNameAsync(name); return(client != null?this.Ok(client) : this.NotFound() as IHttpActionResult); }
public async Task Get_ReturnOkWithClientReceivedFromRepository_When_RepositoryReturnNotNull() { var client = new IdSrvClientDto(); this.ClientRepository.Setup(v => v.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(client); var controller = new ClientController(this.ClientRepository.Object); IHttpActionResult httpResult = await controller.Get(new Guid()); Assert.NotNull(httpResult); Assert.IsInstanceOf <OkNegotiatedContentResult <IdSrvClientDto> >(httpResult); Assert.AreEqual(client, (httpResult as OkNegotiatedContentResult <IdSrvClientDto>).Content); }
public async Task Update_CallServiceGetClientById_When_PassingClientId() { var clientId = Guid.NewGuid(); var client = new IdSrvClientDto(); this.ClientServiceMock .Setup(v => v.GetClientByIdAsync(It.IsAny <Guid>())) .ReturnsAsync(client); var controller = new ClientsController(this.ClientServiceMock.Object); ActionResult result = await controller.Update(clientId); this.ClientServiceMock.Verify(v => v.GetClientByIdAsync(clientId)); }
public async Task GetByNameAsync_ReturnNull_When_PassingIdForNotExisingClient() { await this.InsertDefaultClient(1); await this.InsertDefaultClient(2, false); await this.InsertDefaultClient(3, isBlocked : true); var repository = new SqlCeClientRepository(this.ConnectionFactory); IdSrvClientDto client = await repository.GetByNameAsync("n4"); Assert.IsNull(client); }
public async Task GetByNameAsync_ReturnClient_When_PassingExistingName_And_ClientInDbNotContainsUri() { await this.InsertDefaultClient(1); Guid id = await this.InsertDefaultClient(2, false); await this.InsertDefaultClient(3); var repository = new SqlCeClientRepository(this.ConnectionFactory); IdSrvClientDto client = await repository.GetByNameAsync("n2"); Assert.AreEqual(id, client.Id); Assert.AreEqual($"n2", client.Name); Assert.AreEqual(null, client.Uri); Assert.AreEqual($"p2", client.Secret); }
public async Task InsertInDb_InsertNullAsUri_When_UriNotSpecified() { using (IDbConnection connection = await this.ConnectionFactory.GetConnectionAsync()) { var compiler = new SqlServerCompiler(); var db = new QueryFactory(connection, compiler); this.ConnectionFactory = new SqlCeConnectionFactory(this.TestConnectionString); await db.Query("Clients").InsertAsync(new { Name = "n", Secret = "s" }); IdSrvClientDto client = await db.Query("Clients").Where(new { Name = "n" }).FirstOrDefaultAsync <IdSrvClientDto>(); Assert.IsNull(client.Uri); } }
public async Task <ActionResult> Update(Guid id) { IdSrvClientDto client = await this.ClientService.GetClientByIdAsync(id); if (client == null) { return(this.ViewError("Такого клиента не существует") as ActionResult); } var updateClient = new UpdateIdSrvClientDto { Id = client.Id, Name = client.Name, Secret = client.Secret, Uri = client.Uri, }; return(this.View(updateClient)); }
public async Task CreateAsync_ReturnSuccess_And_CreateNotBlockedUserInDb_When_PassingClientWithoutUri_And_DbNotContainsAnyClient() { var repository = new SqlCeClientRepository(this.ConnectionFactory); RepositoryResponse response = await repository.CreateAsync(new NewIdSrvClientDto { Name = "n", Secret = "s" }); Assert.AreEqual(RepositoryResponse.Success, response); using (IDbConnection connection = await this.ConnectionFactory.GetConnectionAsync()) { var compiler = new SqlServerCompiler(); var db = new QueryFactory(connection, compiler); this.ConnectionFactory = new SqlCeConnectionFactory(this.TestConnectionString); IEnumerable <IdSrvClientDto> clients = await db.Query("Clients").GetAsync <IdSrvClientDto>(); Assert.AreEqual(1, clients.Count()); IdSrvClientDto createdClient = clients.ElementAt(0); Assert.AreEqual("n", createdClient.Name); Assert.AreEqual("s", createdClient.Secret); Assert.IsNull(createdClient.Uri); Assert.IsFalse(createdClient.IsBlocked); } }
public async Task GetByIdAsync_ReturnNull_When_PassingIdForNotExisingClient() { Guid[] ids = new Guid[3]; ids[0] = await this.InsertDefaultClient(1); ids[1] = await this.InsertDefaultClient(2, false); ids[2] = await this.InsertDefaultClient(3, isBlocked : true); var notExistingId = Guid.NewGuid(); while (ids.Contains(notExistingId)) { notExistingId = Guid.NewGuid(); } var repository = new SqlCeClientRepository(this.ConnectionFactory); IdSrvClientDto client = await repository.GetByIdAsync(notExistingId); Assert.IsNull(client); }
/// <inheritdoc/> public async Task <Client> FindClientByIdAsync(string clientId) { IdSrvClientDto clientFromRepo = await this.ClientRepository.GetClientByIdAsync(clientId); if (clientFromRepo == null) { return(null); } var client = new Client { Enabled = !clientFromRepo.IsBlocked, ClientName = clientFromRepo.Name, // ID клиента, также указывается в настройках самого клиента, см. конфигарцию в классе Startup // проектов Site1 и Site2 ClientId = clientFromRepo.Id.ToString(), ClientSecrets = new List <Secret> { new Secret(clientFromRepo.Secret.Sha256()), }, Flow = Flows.ResourceOwner, // Время жизни identity токена в секундах, то есть токена идентификации. // Также есть access токен, то есть токен для доступа к данным, // он обычно имеет короткое время жизни. // Для того, чтобы сервер аутентификации "забывал" логин и пароль пользователя, // надо также выставить время жизни cookie сессии сервера аутентификации, см. // класс Startup. IdentityTokenLifetime = 5 * 60, AccessTokenType = AccessTokenType.Reference, // При входе на сайте через сервер аутентификации в первый раз у пользователя // спрашивают, какие данные сайт может использовать (например, может ли сайт просматривать // профиль пользователя). Для текущих целей не нужно, поэтому пропускаем. RequireConsent = false, AllowedScopes = this.Scopes.Select(s => s.Name).ToList(), // Scope-ы в данном примере не освещаются, по идее с помощью них можно разделить // клиентов (сайты) на области и рулить ими по-отдельности, допускать пользователей // в разные области. Для текущих целей пока не нужно. // AllowAccessToAllScopes = true, }; // Если строка с uri пустая, значит это wpf-клиент (или нечто подобное, то есть не сайт) // Поэтому ставим другой Flow, и добавляем редиректы // (конечно, это можно сделать красивее, но для демонстрации оставил так) if (clientFromRepo.Uri != null) { client.Flow = Flows.Hybrid; // Адрес сайта, куда будет редиректить после входа (по идее должен совпадать с адресом // самого сайта) client.RedirectUris = new List <string> { clientFromRepo.Uri }; // Адрес, на который редиректит после выхода client.PostLogoutRedirectUris = (await this.ClientRepository.GetAllUrisAsync()).ToList(); } else if (this.IsWindowsAuth) { // Если это wpf-клиент и при этом используется windows аутентификация, то необходимо изменить некоторые параметры client.Flow = Flows.Custom; client.AllowedCustomGrantTypes = new List <string> { "winauth" }; } return(client); }
public async Task <IHttpActionResult> Get(Guid id) { IdSrvClientDto client = await this.ClientRepository.GetByIdAsync(id); return(client != null?this.Ok(client) : this.NotFound() as IHttpActionResult); }