public ClientDto GetById(int id, string userName) { Logger.LogInformation(String.Format("Try to get client by id {0}", id)); ClientDto toReturn = null; using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var client = clientRepo.GetById(id); if (client == null || !client.IsValid) { throw new DaOAuthNotFoundException(); } // we need to remove scopes from invalid ressources servers if (client.ClientsScopes != null && client.ClientsScopes.Count() > 0) { var invalidsRs = ExtractInvalidRessourceServerIds(context); client.ClientsScopes = client.ClientsScopes.ToList().Where(cs => !invalidsRs.Contains(cs.Scope.RessourceServerId)).ToList(); } toReturn = client.ToDto(client.UserCreator.UserName.Equals(userName)); } return(toReturn); }
private TokenInfoDto GenerateTokenForRefreshToken(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; if (String.IsNullOrWhiteSpace(tokenInfo.ClientPublicId)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameRefreshToken, Description = errorLocal["RefreshTokenParameterError"] }; } using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } var tokenDetail = JwtService.ExtractToken(new ExtractTokenDto() { Token = tokenInfo.RefreshToken, TokenName = OAuthConvention.RefreshToken }); if (!CheckIfTokenIsValid(tokenDetail, context)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidGrant, Description = errorLocal["RefreshTokenInvalid"] }; } if (!CheckIfScopesAreAuthorizedForClient(tokenDetail.ClientId, tokenInfo.Scope)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidScope, Description = errorLocal["UnauthorizedScope"] }; } toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, tokenDetail.UserName); context.Commit(); } return(toReturn); }
public int CreateReturnUrl(CreateReturnUrlDto toCreate) { this.Validate(toCreate); var idCreated = 0; var resource = this.GetErrorStringLocalizer(); if (!Uri.TryCreate(toCreate.ReturnUrl, UriKind.Absolute, out var u)) { throw new DaOAuthServiceException(resource["CreateReturnUrlReturnUrlIncorrect"]); } using (var context = RepositoriesFactory.CreateContext()) { var userRepo = RepositoriesFactory.GetUserRepository(context); var user = userRepo.GetByUserName(toCreate.UserName); if (user == null || !user.IsValid) { throw new DaOAuthServiceException(resource["CreateReturnUrlInvalidUser"]); } var ucRepo = RepositoriesFactory.GetUserClientRepository(context); var uc = ucRepo.GetUserClientByClientPublicIdAndUserName(toCreate.ClientPublicId, toCreate.UserName); if (uc == null) { throw new DaOAuthServiceException(resource["CreateReturnUrlBadUserNameOrClientId"]); } var clientRepo = RepositoriesFactory.GetClientRepository(context); var client = clientRepo.GetByPublicId(toCreate.ClientPublicId); if (client == null || !client.IsValid) { throw new DaOAuthServiceException(resource["CreateReturnUrlInvalidClient"]); } var existingReturnUrl = client.ClientReturnUrls.FirstOrDefault(c => c.ReturnUrl.Equals(toCreate.ReturnUrl, StringComparison.OrdinalIgnoreCase)); if (existingReturnUrl != null) { idCreated = existingReturnUrl.Id; } else { var returnUrlRepo = RepositoriesFactory.GetClientReturnUrlRepository(context); idCreated = returnUrlRepo.Add(new Domain.ClientReturnUrl() { ClientId = client.Id, ReturnUrl = toCreate.ReturnUrl }); } context.Commit(); } return(idCreated); }
public void Delete(DeleteClientDto toDelete) { Logger.LogInformation(String.Format("Try to create delete by user {0}", toDelete != null ? toDelete.UserName : String.Empty)); Validate(toDelete); using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var userClientRepo = RepositoriesFactory.GetUserClientRepository(context); var userRepo = RepositoriesFactory.GetUserRepository(context); var clientScopeRepo = RepositoriesFactory.GetClientScopeRepository(context); var clientReturnUrlRepo = RepositoriesFactory.GetClientReturnUrlRepository(context); var myUser = userRepo.GetByUserName(toDelete.UserName); if (myUser == null || !myUser.IsValid) { throw new DaOAuthServiceException("DeleteClientInvalidUserName"); } var myClient = clientRepo.GetById(toDelete.Id); if (myClient == null) { throw new DaOAuthServiceException("DeleteClientUnknowClient"); } var myUserClient = userClientRepo .GetUserClientByClientPublicIdAndUserName(myClient.PublicId, toDelete.UserName); if (myUserClient == null || !myUserClient.Client.UserCreator.UserName.Equals(toDelete.UserName, StringComparison.OrdinalIgnoreCase)) { throw new DaOAuthServiceException("DeleteClientWrongUser"); } foreach (var cr in clientReturnUrlRepo.GetAllByClientPublicId(myClient.PublicId).ToList()) { clientReturnUrlRepo.Delete(cr); } foreach (var cs in clientScopeRepo.GetAllByClientId(myClient.Id).ToList()) { clientScopeRepo.Delete(cs); } foreach (var uc in userClientRepo.GetAllByClientId(myClient.Id).ToList()) { userClientRepo.Delete(uc); } userClientRepo.Delete(myUserClient); clientRepo.Delete(myClient); context.Commit(); } }
public int SearchCount(ClientSearchDto criterias) { Validate(criterias, ExtendValidationSearchCriterias); var count = 0; using (var c = RepositoriesFactory.CreateContext()) { var userClientRepo = RepositoriesFactory.GetClientRepository(c); count = userClientRepo.GetAllByCriteriasCount(criterias.Name, criterias.PublicId, true, GetClientTypeId(criterias.ClientType)); } return(count); }
public void DeleteUser(string userName) { Logger.LogInformation($"delete user {userName}"); using (var context = RepositoriesFactory.CreateContext()) { var userRepository = RepositoriesFactory.GetUserRepository(context); var clientRepository = RepositoriesFactory.GetClientRepository(context); var userClientRepository = RepositoriesFactory.GetUserClientRepository(context); var user = userRepository.GetByUserName(userName); var local = this.GetErrorStringLocalizer(); if (user == null || !user.IsValid) { throw new DaOAuthServiceException(local["DeleteUserNoUserFound"]); } var clients = clientRepository.GetAllClientsByIdCreator(user.Id); IList <Client> toDeleteClients = new List <Client>(); IList <UserClient> toDeleteUsersClients = new List <UserClient>(); foreach (var client in clients) { foreach (var uc in userClientRepository.GetAllByClientId(client.Id)) { toDeleteUsersClients.Add(uc); } toDeleteClients.Add(client); } foreach (var uc in toDeleteUsersClients) { userClientRepository.Delete(uc); } foreach (var c in toDeleteClients) { clientRepository.Delete(c); } userRepository.Delete(user); context.Commit(); } }
private TokenInfoDto GenerateTokenForClientCredentailsGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } if (!CheckIfScopesAreAuthorizedForClient(myClient.PublicId, tokenInfo.Scope)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidScope, Description = errorLocal["UnauthorizedScope"] }; } var accesToken = JwtService.GenerateToken(new CreateTokenDto() { ClientPublicId = myClient.PublicId, Scope = tokenInfo.Scope, SecondsLifeTime = Configuration.AccesTokenLifeTimeInSeconds, TokenName = OAuthConvention.AccessToken, UserName = String.Empty }); toReturn = new TokenInfoDto() { AccessToken = accesToken.Token, ExpireIn = Configuration.AccesTokenLifeTimeInSeconds, Scope = tokenInfo.Scope, TokenType = OAuthConvention.AccessToken }; } return(toReturn); }
public int CreateUserClient(CreateUserClientDto toCreate) { Validate(toCreate); var id = 0; var local = GetErrorStringLocalizer(); using (var context = RepositoriesFactory.CreateContext()) { var userClientRepo = RepositoriesFactory.GetUserClientRepository(context); var clientRepo = RepositoriesFactory.GetClientRepository(context); var userRepo = RepositoriesFactory.GetUserRepository(context); var user = userRepo.GetByUserName(toCreate.UserName); if (user == null || !user.IsValid) { throw new DaOAuthServiceException(local["CreateUserClientInvalidUserName"]); } var client = clientRepo.GetByPublicId(toCreate.ClientPublicId); if (client == null || !client.IsValid) { throw new DaOAuthServiceException(local["CreateUserClientInvalidClientPublicId"]); } var uc = userClientRepo.GetUserClientByClientPublicIdAndUserName(toCreate.ClientPublicId, toCreate.UserName); if (uc != null) { throw new DaOAuthServiceException(local["CreateUserClientClientAlreadyRegister"]); } id = userClientRepo.Add(new UserClient() { ClientId = client.Id, CreationDate = DateTime.Now, IsActif = toCreate.IsActif, UserId = user.Id }); context.Commit(); } return(id); }
private bool CheckIfClientIsValid(string clientPublicId, Uri requestRedirectUri, EClientType clientType) { using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var clientReturnUrlRepo = RepositoriesFactory.GetClientReturnUrlRepository(context); var client = clientRepo.GetByPublicId(clientPublicId); if (client == null) { return(false); } if (!client.IsValid) { return(false); } if (client.ClientTypeId != (int)clientType) { return(false); } IList <Uri> clientUris = new List <Uri>(); foreach (var uri in clientReturnUrlRepo.GetAllByClientPublicId(clientPublicId)) { clientUris.Add(new Uri(uri.ReturnUrl, UriKind.Absolute)); } if (!clientUris.Contains(requestRedirectUri)) { return(false); } } return(true); }
public IEnumerable <ClientDto> Search(ClientSearchDto criterias) { Logger.LogInformation("Search clients"); Validate(criterias, ExtendValidationSearchCriterias); IList <Client> clients = null; var clientTypeId = GetClientTypeId(criterias.ClientType); using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); clients = clientRepo.GetAllByCriterias( criterias.Name, criterias.PublicId, true, clientTypeId, criterias.Skip, criterias.Limit ).ToList(); var invalidsRs = ExtractInvalidRessourceServerIds(context); foreach (var c in clients) { if (c.ClientsScopes != null && c.ClientsScopes.Count() > 0) { c.ClientsScopes = c.ClientsScopes.ToList().Where(cs => !invalidsRs.Contains(cs.Scope.RessourceServerId)).ToList(); } } } return(clients != null?clients.ToDto() : new List <ClientDto>()); }
private TokenInfoDto GenerateTokenForPasswordGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; if (String.IsNullOrWhiteSpace(tokenInfo.ParameterUsername)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["UserNameParameterError"] }; } if (String.IsNullOrWhiteSpace(tokenInfo.Password)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["PasswordParameterError"] }; } using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } var repo = RepositoriesFactory.GetUserRepository(context); var user = repo.GetByUserName(tokenInfo.ParameterUsername); if (user == null || !user.IsValid || !EncryptonService.AreEqualsSha256( String.Concat(Configuration.PasswordSalt, tokenInfo.Password), user.Password)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidGrant, Description = errorLocal["UserCredentialsIncorrects"] }; } if (!CheckIfScopesAreAuthorizedForClient(myClient.PublicId, tokenInfo.Scope)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidScope, Description = errorLocal["UnauthorizedScope"] }; } toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, tokenInfo.ParameterUsername); context.Commit(); } return(toReturn); }
private TokenInfoDto GenerateTokenForAuthorizationCodeGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal) { TokenInfoDto toReturn = null; if (String.IsNullOrWhiteSpace(tokenInfo.ClientPublicId)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["ClientIdParameterError"] }; } using (var context = RepositoriesFactory.CreateContext()) { var clientRepo = RepositoriesFactory.GetClientRepository(context); var myClient = clientRepo.GetByPublicId(tokenInfo.ClientPublicId); if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameUnauthorizedClient, Description = errorLocal["UnauthorizedClient"] }; } if (String.IsNullOrWhiteSpace(tokenInfo.CodeValue)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["CodeParameterError"] }; } if (String.IsNullOrWhiteSpace(tokenInfo.RedirectUrl) || !Uri.TryCreate(tokenInfo.RedirectUrl, UriKind.Absolute, out var myUri)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidRequest, Description = errorLocal["ReturnUrlParameterError"] }; } if (!CheckIfClientValidForToken(myClient, tokenInfo.RedirectUrl, OAuthConvention.ResponseTypeCode)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidClient, Description = errorLocal["AskTokenInvalidClient"] }; } if (!CheckIfCodeIsValid(tokenInfo.ClientPublicId, tokenInfo.Scope, tokenInfo.CodeValue, context, out var userName)) { throw new DaOAuthTokenException() { Error = OAuthConvention.ErrorNameInvalidGrant, Description = errorLocal["AskTokenInvalidGrant"] }; } toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, userName); context.Commit(); } return(toReturn); }
public ClientDto Update(UpdateClientDto toUpdate) { IList <ValidationResult> ExtendValidation(UpdateClientDto toValidate) { var resource = this.GetErrorStringLocalizer(); IList <ValidationResult> result = new List <ValidationResult>(); if (toValidate.ReturnUrls == null || toValidate.ReturnUrls.Count() == 0) { result.Add(new ValidationResult(resource["UpdateClientDtoDefaultReturnUrlRequired"])); } if (toValidate.ReturnUrls != null) { foreach (var ur in toValidate.ReturnUrls) { if (!Uri.TryCreate(ur, UriKind.Absolute, out var u)) { result.Add(new ValidationResult(resource["UpdateClientDtoReturnUrlIncorrect"])); } } } if (toValidate.ClientType != ClientTypeName.Confidential && toValidate.ClientType != ClientTypeName.Public) { result.Add(new ValidationResult(resource["UpdateClientDtoTypeIncorrect"])); } if (!toValidate.ClientSecret.IsMatchClientSecretPolicy()) { result.Add(new ValidationResult(resource["UpdateClientDtoClientSecretDontMatchPolicy"])); } return(result); } Logger.LogInformation(String.Format("Try to update client for user {0}", toUpdate != null ? toUpdate.UserName : String.Empty)); Validate(toUpdate, ExtendValidation); using (var context = RepositoriesFactory.CreateContext()) { var resource = this.GetErrorStringLocalizer(); var clientRepo = RepositoriesFactory.GetClientRepository(context); var userClientRepo = RepositoriesFactory.GetUserClientRepository(context); var scopeRepo = RepositoriesFactory.GetScopeRepository(context); var userRepo = RepositoriesFactory.GetUserRepository(context); var clientReturnUrlRepo = RepositoriesFactory.GetClientReturnUrlRepository(context); var clientScopeRepo = RepositoriesFactory.GetClientScopeRepository(context); var myClient = clientRepo.GetById(toUpdate.Id); if (myClient == null || !myClient.IsValid) { throw new DaOAuthServiceException(resource["UpdateClientInvalidClient"]); } var ucs = userClientRepo.GetAllByCriterias(toUpdate.UserName, toUpdate.Name, null, null, 0, 50); if (ucs != null && ucs.Count() > 0) { var myUc = ucs.First(); if (myUc.ClientId != myClient.Id) { throw new DaOAuthServiceException(resource["UpdateClientNameAlreadyUsed"]); } } var cl = clientRepo.GetByPublicId(toUpdate.PublicId); if (cl != null && cl.Id != myClient.Id) { throw new DaOAuthServiceException(resource["UpdateClientpublicIdAlreadyUsed"]); } var scopes = scopeRepo.GetAll(); if (toUpdate.ScopesIds != null) { IList <int> ids = scopes.Select(s => s.Id).ToList(); foreach (var scopeId in toUpdate.ScopesIds) { if (!ids.Contains(scopeId)) { throw new DaOAuthServiceException(resource["UpdateClientScopeDontExists"]); } } } var myUser = userRepo.GetByUserName(toUpdate.UserName); if (myUser == null || !myUser.IsValid) { throw new DaOAuthServiceException(resource["UpdateClientInvalidUser"]); } var myUserClient = userClientRepo. GetUserClientByClientPublicIdAndUserName(myClient.PublicId, toUpdate.UserName); if (myUserClient == null || !myUserClient.Client.UserCreator.UserName.Equals(toUpdate.UserName, StringComparison.OrdinalIgnoreCase)) { throw new DaOAuthServiceException(resource["UpdateClientInvalidUser"]); } // update returns urls foreach (var ru in clientReturnUrlRepo.GetAllByClientPublicId(myClient.PublicId).ToList()) { clientReturnUrlRepo.Delete(ru); } foreach (var ru in toUpdate.ReturnUrls) { clientReturnUrlRepo.Add(new ClientReturnUrl() { ClientId = myClient.Id, ReturnUrl = ru }); } // updates clients scopes foreach (var s in clientScopeRepo.GetAllByClientId(myClient.Id).ToList()) { clientScopeRepo.Delete(s); } if (toUpdate.ScopesIds != null) { foreach (var s in toUpdate.ScopesIds) { clientScopeRepo.Add(new ClientScope() { ClientId = myClient.Id, ScopeId = s }); } } // update client myClient.ClientSecret = toUpdate.ClientSecret; myClient.ClientTypeId = toUpdate.ClientType.Equals( ClientTypeName.Confidential, StringComparison.OrdinalIgnoreCase) ? (int)EClientType.CONFIDENTIAL : (int)EClientType.PUBLIC; myClient.Description = toUpdate.Description; myClient.Name = toUpdate.Name; myClient.PublicId = toUpdate.PublicId; clientRepo.Update(myClient); context.Commit(); return(myClient.ToDto(true)); } }
public int CreateClient(CreateClientDto toCreate) { IList <ValidationResult> ExtendValidation(CreateClientDto toValidate) { var resource = this.GetErrorStringLocalizer(); IList <ValidationResult> result = new List <ValidationResult>(); if (toValidate.ReturnUrls == null || toValidate.ReturnUrls.Count() == 0) { result.Add(new ValidationResult(resource["CreateClientDtoDefaultReturnUrlRequired"])); } foreach (var ur in toValidate.ReturnUrls) { if (!Uri.TryCreate(ur, UriKind.Absolute, out var u)) { result.Add(new ValidationResult(resource["CreateClientDtoReturnUrlIncorrect"])); } } if (toValidate.ClientType != ClientTypeName.Confidential && toValidate.ClientType != ClientTypeName.Public) { result.Add(new ValidationResult(resource["CreateClientDtoTypeIncorrect"])); } using (var context = RepositoriesFactory.CreateContext()) { var userRepo = RepositoriesFactory.GetUserRepository(context); var user = userRepo.GetByUserName(toValidate.UserName); if (user == null || !user.IsValid) { result.Add(new ValidationResult(String.Format(resource["CreateClientDtoInvalidUser"], toCreate.UserName))); } var userClientRepo = RepositoriesFactory.GetUserClientRepository(context); if (!String.IsNullOrEmpty(toValidate.Name) && userClientRepo.GetAllByCriteriasCount(toValidate.UserName, toValidate.Name, null, null) > 0) { result.Add(new ValidationResult(resource["CreateClientDtoNameAlreadyUse"])); } } return(result); } Logger.LogInformation(String.Format("Try to create client by user {0}", toCreate != null ? toCreate.UserName : String.Empty)); this.Validate(toCreate, ExtendValidation); using (var context = RepositoriesFactory.CreateContext()) { var returnUrlRepo = RepositoriesFactory.GetClientReturnUrlRepository(context); var clientRepo = RepositoriesFactory.GetClientRepository(context); var userClientRepo = RepositoriesFactory.GetUserClientRepository(context); var userRepo = RepositoriesFactory.GetUserRepository(context); var clientScopeRepo = RepositoriesFactory.GetClientScopeRepository(context); var user = userRepo.GetByUserName(toCreate.UserName); var client = new Client() { ClientSecret = RandomService.GenerateRandomString(16), ClientTypeId = toCreate.ClientType.Equals(ClientTypeName.Confidential, StringComparison.OrdinalIgnoreCase) ? (int)EClientType.CONFIDENTIAL : (int)EClientType.PUBLIC, CreationDate = DateTime.Now, Description = toCreate.Description, IsValid = true, Name = toCreate.Name, PublicId = RandomService.GenerateRandomString(16), UserCreatorId = user.Id }; clientRepo.Add(client); foreach (var ur in toCreate.ReturnUrls) { var clientReturnUrl = new ClientReturnUrl() { ReturnUrl = ur, ClientId = client.Id }; returnUrlRepo.Add(clientReturnUrl); } var userClient = new UserClient() { ClientId = client.Id, CreationDate = DateTime.Now, IsActif = true, RefreshToken = String.Empty, UserId = user.Id }; userClientRepo.Add(userClient); if (toCreate.ScopesIds != null) { foreach (var sId in toCreate.ScopesIds) { clientScopeRepo.Add(new ClientScope() { ClientId = client.Id, ScopeId = sId }); } } context.Commit(); return(client.Id); } }