Skip to content

Commit

Permalink
Ticket #744 : Fix some issues in the SQL SUGAR library
Browse files Browse the repository at this point in the history
  • Loading branch information
thabart committed May 27, 2024
1 parent c7765d7 commit ecda1e1
Show file tree
Hide file tree
Showing 45 changed files with 294 additions and 116 deletions.
43 changes: 40 additions & 3 deletions src/IdServer/SimpleIdServer.IdServer.Startup/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using NeoSmart.Caching.Sqlite.AspNetCore;
using SimpleIdServer.Configuration;
using SimpleIdServer.Did.Key;
Expand All @@ -30,10 +31,12 @@
using SimpleIdServer.IdServer.Startup.Configurations;
using SimpleIdServer.IdServer.Startup.Converters;
using SimpleIdServer.IdServer.Store.EF;
using SimpleIdServer.IdServer.Store.SqlSugar.Models;
using SimpleIdServer.IdServer.Swagger;
using SimpleIdServer.IdServer.TokenTypes;
using SimpleIdServer.IdServer.VerifiablePresentation;
using SimpleIdServer.IdServer.WsFederation;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -57,7 +60,41 @@
"`Value` longblob NOT NULL," +
"PRIMARY KEY(`Id`)," +
"KEY `Index_ExpiresAtTime` (`ExpiresAtTime`)" +
")";
")";

/*
static void Test()
{
var connectionConfig = new ConnectionConfig
{
DbType = DbType.SqlServer,
ConnectionString = "Data Source=.;Initial Catalog=IdServer;Integrated Security=True;TrustServerCertificate=True"
};
var client = new SqlSugarClient(connectionConfig, it =>
{
it.Aop.OnLogExecuted = (sql, para) =>
{
var ss = UtilMethods.GetNativeSql(sql, para);
string ss2 = "";
};
});
client.BeginTran();
client.Insertable(new SugarUserSession
{
AuthenticationDateTime = DateTime.Now,
ExpirationDateTime = DateTime.Now,
Realm = "master",
SerializedClientIds = "",
SessionId = "id",
State = UserSessionStates.Active,
UserId = "91ad04aa-de65-4cb5-8717-7c4a97c47632",
IsClientsNotified = false
}).ExecuteCommand();
client.CommitTran();
}
Test();
*/

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
var builder = WebApplication.CreateBuilder(args);
Expand Down Expand Up @@ -300,8 +337,8 @@ void ConfigureStorage(DbContextOptionsBuilder b)

void ConfigureDataProtection(IDataProtectionBuilder dataProtectionBuilder)
{
// TODO : UPDATE !!
dataProtectionBuilder.PersistKeysToDbContext<StoreDbContext>();
dataProtectionBuilder.Services.PersistKeysToSqlSugar();
// dataProtectionBuilder.PersistKeysToDbContext<StoreDbContext>();
}

void SeedData(WebApplication application, string scimBaseUrl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,17 @@ public async Task<SearchResult<ApiResource>> Search(string realm, SearchRequest
.Includes(p => p.Realms)
.Includes(p => p.Scopes)
.Where(p => p.Realms.Any(r => r.RealmsName == realm));
query = query.OrderByDescending(a => a.UpdateDateTime);
/*
if (!string.IsNullOrWhiteSpace(request.Filter))
query = query.Where(request.Filter);
if (!string.IsNullOrWhiteSpace(request.OrderBy))
query = query.OrderBy(request.OrderBy);
else
query = query.OrderBy(r => r.Name);
*/

var nb = query.Count();

var apiResources = await query.Skip(request.Skip.Value).Take(request.Take.Value).ToListAsync(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,14 @@ public async Task<SearchResult<AuditEvent>> Search(string realm, SearchAuditing
.Where(r => r.Realm == realm);
if (request.DisplayOnlyErrors)
query = query.Where(r => r.IsError);

query = query.OrderByDescending(a => a.CreateDateTime);
/*
if (!string.IsNullOrWhiteSpace(request.Filter))
query = query.Where(request.Filter);
if (!string.IsNullOrWhiteSpace(request.OrderBy))
query = query.OrderBy(request.OrderBy);
*/

var nb = query.Count();
var result = await query.Skip(request.Skip.Value).Take(request.Take.Value).ToListAsync(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ public async Task<SearchResult<AuthenticationSchemeProvider>> Search(string real
var query = _dbContext.Client.Queryable<SugarAuthenticationSchemeProvider>()
.Includes(p => p.Realms)
.Where(p => p.Realms.Any(r => r.RealmsName == realm));
query = query.OrderByDescending(r => r.CreateDateTime);
/*
if (!string.IsNullOrWhiteSpace(request.Filter))
query = query.Where(request.Filter);
if (!string.IsNullOrWhiteSpace(request.OrderBy))
query = query.OrderBy(request.OrderBy);
*/

var nb = query.Count();
var idProviders = await query.Skip(request.Skip.Value).Take(request.Take.Value).ToListAsync(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,17 @@ public async Task<SearchResult<CertificateAuthority>> Search(string realm, Searc
var query = _dbContext.Client.Queryable<SugarCertificateAuthority>()
.Includes(p => p.Realms)
.Where(p => p.Realms.Any(r => r.RealmsName == realm));
/*
if (!string.IsNullOrWhiteSpace(request.Filter))
query = query.Where(request.Filter);
if (!string.IsNullOrWhiteSpace(request.OrderBy))
query = query.OrderBy(request.OrderBy);
else
query = query.OrderByDescending(c => c.UpdateDateTime);
*/

query = query.OrderByDescending(c => c.UpdateDateTime);
var nb = query.Count();
var cas = await query.Skip(request.Skip.Value).Take(request.Take.Value).ToListAsync(cancellationToken);
return new SearchResult<CertificateAuthority>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,15 @@ public async Task<SearchResult<Client>> Search(string realm, SearchRequest reque
.Includes(p => p.Realms)
.Includes(p => p.Scopes)
.Where(p => p.Realms.Any(r => r.RealmsName == realm));
result = result.OrderByDescending(c => c.UpdateDateTime);
/*
if (!string.IsNullOrWhiteSpace(request.Filter))
result = result.Where(request.Filter);

if (!string.IsNullOrWhiteSpace(request.OrderBy))
result = result.OrderBy(request.OrderBy);
else
result = result.OrderByDescending(r => r.UpdateDateTime);
*/

var nb = result.Count();
var clients = await result.Skip(request.Skip.Value).Take(request.Take.Value).ToListAsync();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SimpleIdServer.IdServer.Store.SqlSugar;

namespace Microsoft.AspNetCore.DataProtection;

public static class DataProtectionBuilderExtensions
{
public static void PersistKeysToSqlSugar(this IServiceCollection services)
{
services.AddSingleton((Func<IServiceProvider, IConfigureOptions<KeyManagementOptions>>)delegate (IServiceProvider services)
{
return new ConfigureOptions<KeyManagementOptions>(delegate (KeyManagementOptions options)
{
options.XmlRepository = new SqlSugarXmlRepository(services);
});
});
}
}
16 changes: 11 additions & 5 deletions src/IdServer/SimpleIdServer.IdServer.Store.SqlSugar/DbContext.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.Extensions.Options;
using SimpleIdServer.IdServer.Store.SqlSugar.Models;
using SqlSugar;
using System.ComponentModel.DataAnnotations.Schema;

namespace SimpleIdServer.IdServer.Store.SqlSugar;

public class DbContext : IDisposable
{
private readonly SqlSugarClient _client;
private readonly SqlSugarScope _client;

public DbContext(IOptions<SqlSugarOptions> options)
{
var connectionConfig = options.Value.ConnectionConfig;
connectionConfig.IsAutoCloseConnection = true;
connectionConfig.DbType = DbType.SqlServer;
_client = new SqlSugarClient(connectionConfig, it =>
_client = new SqlSugarScope(connectionConfig, it =>
{
it.Aop.OnLogExecuted = (sql, para) =>
{
var ss = UtilMethods.GetNativeSql(sql, para);

string ss2 = "";
};
});
UserSessions = new SimpleClient<SugarUserSession>(_client);
Users = new SimpleClient<SugarUser>();
}

public SqlSugarClient Client
public SimpleClient<SugarUserSession> UserSessions { get; set; }
public SimpleClient<SugarUser> Users { get; set; }

public SqlSugarScope Client
{
get
{
Expand All @@ -38,4 +42,6 @@ public void Dispose()
{
_client?.Dispose();
}

public Guid Id { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,17 @@ public async Task<SearchResult<Group>> Search(string realm, SearchGroupsRequest
{
var query = _dbContext.Client.Queryable<SugarGroup>()
.Includes(c => c.Realms)
.Where(c => c.Realms.Any(r => r.RealmsName == realm) && (!request.OnlyRoot || request.OnlyRoot && c.Name == c.FullPath));
.Where(c => c.Realms.Any(r => r.RealmsName == realm) && (request.OnlyRoot == false || request.OnlyRoot == true && c.Name == c.FullPath));
/*
if (!string.IsNullOrWhiteSpace(request.Filter))
query = query.Where(request.Filter);
if (!string.IsNullOrWhiteSpace(request.OrderBy))
query = query.OrderBy(request.OrderBy);
else
query = query.OrderBy(q => q.FullPath);

*/
query = query.OrderByDescending(r => r.UpdateDateTime);
var nb = query.Count();
var groups = await query.Skip(request.Skip.Value).Take(request.Take.Value).ToListAsync();
return new SearchResult<Group>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ public async Task<SearchResult<IdentityProvisioning>> Search(string realm, Searc
var query = _dbContext.Client.Queryable<SugarIdentityProvisioning>()
.Includes(p => p.Realms)
.Where(p => p.Realms.Any(r => r.RealmsName == realm));
/*
if (!string.IsNullOrWhiteSpace(request.Filter))
query = query.Where(request.Filter);
if (!string.IsNullOrWhiteSpace(request.OrderBy))
query = query.OrderBy(request.OrderBy);

*/
query = query.OrderByDescending(c => c.UpdateDateTime);
var nb = query.Count();
var idProviders = await query.Skip(request.Skip.Value).Take(request.Take.Value).ToListAsync();
return new SearchResult<IdentityProvisioning>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace SimpleIdServer.IdServer.Store.SqlSugar.Models
[SugarTable("Acrs")]
public class SugarAuthenticationContextClassReference
{
[SugarColumn(IsPrimaryKey = true)]
public string Id { get; set; } = null!;
public string Name { get; set; } = null;
public string DisplayName { get; set; } = null;
Expand All @@ -34,8 +35,9 @@ public AuthenticationContextClassReference ToDomain()
UpdateDateTime = UpdateDateTime,
RegistrationWorkflowId = RegistrationWorkflowId,
AuthenticationMethodReferences = AuthenticationMethodReferences.Split(','),
Realms = Realms.Select(r => r.ToDomain()).ToList(),
Clients
Realms = Realms == null ? new List<Realm>() : Realms.Select(r => r.ToDomain()).ToList(),
Clients = Clients == null ? new List<Client>() : Clients.Select(c => c.ToDomain()).ToList(),
RegistrationWorkflow = RegistrationWorkflow?.ToDomain()
};
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ public AuthenticationSchemeProvider ToDomain()
CreateDateTime = CreateDateTime,
UpdateDateTime = UpdateDateTime,
AuthSchemeProviderDefinition = AuthSchemeProviderDefinition?.ToDomain(),
Realms = Realms.Select(r => r.ToDomain()).ToList(),
Mappers = Mappers.Select(m => m.ToDomain()).ToList()
Realms = Realms == null ? Realms.Select(r => r.ToDomain()).ToList() : new List<Realm>(),
Mappers = Mappers == null ? new List<AuthenticationSchemeProviderMapper>() : Mappers.Select(m => m.ToDomain()).ToList()
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class SugarAuthenticationSchemeProviderMapper
public string? TargetUserAttribute { get; set; } = null;
public string? TargetUserProperty { get; set; } = null;
public string IdProviderId { get; set; } = null!;
[Navigate(NavigateType.ManyToOne, nameof(IdProviderId)]
[Navigate(NavigateType.ManyToOne, nameof(IdProviderId))]
public AuthenticationSchemeProvider IdProvider { get; set; } = null!;

public AuthenticationSchemeProviderMapper ToDomain()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ public class SugarAuthorizedResource
public string? Audience { get; set; } = null;
public string? AuthorizedScopeId { get; set; } = null;

public static SugarAuthorizedResource Transform(AuthorizedResource a)
{
return new SugarAuthorizedResource
{
Audience = a.Audience,
Resource = a.Resource
};
}

public AuthorizedResource ToDomain()
{
return new AuthorizedResource
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,21 @@ public class SugarAuthorizedScope
[Navigate(NavigateType.OneToMany, nameof(SugarAuthorizedResource.AuthorizedScopeId))]
public List<SugarAuthorizedResource> AuthorizedResources { get; set; }

public static SugarAuthorizedScope Transform(AuthorizedScope authorizedScope)
{
return new SugarAuthorizedScope
{
AuthorizedResources = authorizedScope.AuthorizedResources == null ? new List<SugarAuthorizedResource>() : authorizedScope.AuthorizedResources.Select(a => SugarAuthorizedResource.Transform(a)).ToList(),
Scope = authorizedScope.Scope
};
}

public AuthorizedScope ToDomain()
{
return new AuthorizedScope
{
Scope = Scope,
AuthorizedResources = AuthorizedResources.Select(r => r.ToDomain()).ToList()
AuthorizedResources = AuthorizedResources == null ? new List<AuthorizedResource>() : AuthorizedResources.Select(r => r.ToDomain()).ToList()
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public BCAuthorize ToDomain()
Realm = Realm,
SerializedAuthorizationDetails = SerializedAuthorizationDetails,
Scopes = Scopes == null ? new List<string>() : Scopes.Split(','),
Histories = Histories.Select(h => h.ToDomain()).ToList()
Histories = Histories == null ? new List<BCAuthorizeHistory>() : Histories.Select(h => h.ToDomain()).ToList()
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

namespace SimpleIdServer.IdServer.Store.SqlSugar.Models;

[SugarTable("CertificateAuthorities")]
public class SugarCertificateAuthority
{
[SugarColumn(IsPrimaryKey = true)]
Expand Down Expand Up @@ -43,7 +44,7 @@ public CertificateAuthority ToDomain()
EndDateTime = EndDateTime,
UpdateDateTime = UpdateDateTime,
Realms = Realms.Select(r => r.ToDomain()).ToList(),
ClientCertificates = ClientCertificates.Select(c => c.ToDomain()).ToList()
ClientCertificates = ClientCertificates == null ? new List<ClientCertificate>() : ClientCertificates.Select(c => c.ToDomain()).ToList()
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,11 @@ public Client ToDomain()
DefaultAcrValues = DefaultAcrValues == null ? new List<string>() : DefaultAcrValues.Split(','),
Contacts = Contacts == null ? new List<string>() : Contacts.Split(','),
AuthorizationDataTypes = AuthorizationDataTypes == null ? new List<string>() : AuthorizationDataTypes.Split(','),
Realms = Realms.Select(r => r.ToDomain()).ToList(),
Translations = Translations.Select(r => r.ToDomain()).ToList(),
DeviceAuthCodes = DeviceAuthCodes.Select(r => r.ToDomain()).ToList(),
SerializedJsonWebKeys = SerializedJsonWebKeys.Select(j => j.ToDomain()).ToList(),
Scopes = Scopes.Select(s => s.ToDomain()).ToList(),
Realms = Realms == null ? new List<Realm>() : Realms.Select(r => r.ToDomain()).ToList(),
Translations = Translations == null ? new List<Translation>() : Translations.Select(r => r.ToDomain()).ToList(),
DeviceAuthCodes = DeviceAuthCodes == null ? new List<DeviceAuthCode>() : DeviceAuthCodes.Select(r => r.ToDomain()).ToList(),
SerializedJsonWebKeys = SerializedJsonWebKeys == null ? new List<ClientJsonWebKey>() : SerializedJsonWebKeys.Select(j => j.ToDomain()).ToList(),
Scopes = Scopes == null ? new List<Scope>() : Scopes.Select(s => s.ToDomain()).ToList(),
Id = Id
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public ConfigurationDefinition ToDomain()
CreateDateTime = CreateDateTime,
UpdateDateTime = UpdateDateTime,
FullQualifiedName = FullQualifiedName,
Records = ConfigurationDefinitionRecords.Select(r => r.ToDomain()).ToList()
Records = ConfigurationDefinitionRecords == null ? new List<ConfigurationDefinitionRecord>() : ConfigurationDefinitionRecords.Select(r => r.ToDomain()).ToList()
};
}
}
Loading

0 comments on commit ecda1e1

Please sign in to comment.