Skip to content

Commit a90323f

Browse files
Fix get client & create "DistributedCache" table (postgre)
1 parent 1a8d216 commit a90323f

10 files changed

Lines changed: 93 additions & 8 deletions

File tree

src/IdServer/SimpleIdServer.IdServer.Startup/Program.cs

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
using Microsoft.Extensions.Configuration;
1515
using Microsoft.Extensions.DependencyInjection;
1616
using Microsoft.Extensions.Hosting;
17+
using MySqlConnector;
1718
using NeoSmart.Caching.Sqlite.AspNetCore;
1819
using SimpleIdServer.Configuration;
1920
using SimpleIdServer.Did.Key;
@@ -39,6 +40,7 @@
3940
using SimpleIdServer.IdServer.WsFederation;
4041
using System;
4142
using System.Collections.Generic;
43+
using System.Data.Common;
4244
using System.Linq;
4345
using System.Net;
4446
using System.Security.Cryptography.X509Certificates;
@@ -63,6 +65,20 @@
6365
"KEY `Index_ExpiresAtTime` (`ExpiresAtTime`)" +
6466
")";
6567

68+
const string PostgreCreateSchemaAndTableSql =
69+
$"""
70+
CREATE SCHEMA IF NOT EXISTS "public";
71+
CREATE TABLE IF NOT EXISTS "public"."DistributedCache"
72+
(
73+
"Id" text COLLATE pg_catalog."default" NOT NULL,
74+
"Value" bytea,
75+
"ExpiresAtTime" timestamp with time zone,
76+
"SlidingExpirationInSeconds" double precision,
77+
"AbsoluteExpiration" timestamp with time zone,
78+
CONSTRAINT "DistCache_pkey" PRIMARY KEY ("Id")
79+
)
80+
""";
81+
6682
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
6783
var builder = WebApplication.CreateBuilder(args);
6884
builder.Configuration
@@ -498,6 +514,13 @@ async void SeedData(WebApplication application, string scimBaseUrl)
498514
void EnableIsolationLevel(StoreDbContext dbContext)
499515
{
500516
if (dbContext.Database.IsInMemory()) return;
517+
EnableSqlServer(dbContext);
518+
EnableMysql(dbContext);
519+
EnablePostgre(dbContext);
520+
}
521+
522+
void EnableSqlServer(StoreDbContext dbContext)
523+
{
501524
var dbConnection = dbContext.Database.GetDbConnection();
502525
var sqlConnection = dbConnection as SqlConnection;
503526
if (sqlConnection != null)
@@ -509,17 +532,32 @@ void EnableIsolationLevel(StoreDbContext dbContext)
509532
cmd = sqlConnection.CreateCommand();
510533
cmd.CommandText = SQLServerCreateTableFormat;
511534
cmd.ExecuteNonQuery();
512-
return;
513535
}
536+
}
514537

538+
void EnableMysql(StoreDbContext dbContext)
539+
{
540+
var dbConnection = dbContext.Database.GetDbConnection();
515541
var mysqlConnection = dbConnection as MySqlConnector.MySqlConnection;
516542
if (mysqlConnection != null)
517543
{
518544
if (mysqlConnection.State != System.Data.ConnectionState.Open) mysqlConnection.Open();
519545
var cmd = mysqlConnection.CreateCommand();
520546
cmd.CommandText = MYSQLCreateTableFormat;
521547
cmd.ExecuteNonQuery();
522-
return;
548+
}
549+
}
550+
551+
void EnablePostgre(StoreDbContext dbContext)
552+
{
553+
var dbConnection = dbContext.Database.GetDbConnection();
554+
var postgreconnection = dbConnection as Npgsql.NpgsqlConnection;
555+
if(postgreconnection != null)
556+
{
557+
if (postgreconnection.State != System.Data.ConnectionState.Open) postgreconnection.Open();
558+
var cmd = postgreconnection.CreateCommand();
559+
cmd.CommandText = PostgreCreateSchemaAndTableSql;
560+
cmd.ExecuteNonQuery();
523561
}
524562
}
525563

src/IdServer/SimpleIdServer.IdServer.Store.EF/ClientRepository.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@ public ClientRepository(StoreDbContext dbContext)
1717
_dbContext = dbContext;
1818
}
1919

20+
public Task<Client> GetById(string realm, string id, CancellationToken cancellationToken)
21+
{
22+
return _dbContext.Clients
23+
.Include(c => c.Scopes).ThenInclude(s => s.ClaimMappers)
24+
.Include(c => c.SerializedJsonWebKeys)
25+
.Include(c => c.Translations)
26+
.Include(c => c.Realms)
27+
.SingleOrDefaultAsync(c => c.Id == id && c.Realms.Any(r => r.Name == realm), cancellationToken);
28+
}
29+
2030
public Task<Client> GetByClientId(string realm, string clientId, CancellationToken cancellationToken)
2131
{
2232
return _dbContext.Clients

src/IdServer/SimpleIdServer.IdServer.Store.SqlSugar/ClientRepository.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,17 @@ public async Task<List<Client>> GetAll(string realm, List<string> clientIds, Can
7171
return result.Select(r => r.ToDomain()).ToList();
7272
}
7373

74+
public async Task<Client> GetById(string realm, string id, CancellationToken cancellationToken)
75+
{
76+
var result = await _dbContext.Client.Queryable<SugarClient>()
77+
.Includes(c => c.ClientScopes, c => c.Scope, s => s.ClaimMappers)
78+
.Includes(c => c.SerializedJsonWebKeys)
79+
.Includes(c => c.Translations)
80+
.Includes(c => c.Realms)
81+
.FirstAsync(c => c.Id == id && c.Realms.Any(r => r.RealmsName == realm), cancellationToken);
82+
return result?.ToDomain();
83+
}
84+
7485
public async Task<Client> GetByClientId(string realm, string clientId, CancellationToken cancellationToken)
7586
{
7687
var result = await _dbContext.Client.Queryable<SugarClient>()

src/IdServer/SimpleIdServer.IdServer.Website/Pages/Client.razor

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@
9494
notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = act.ErrorMessage });
9595
StateHasChanged();
9696
});
97-
dispatcher.Dispatch(new GetClientAction { ClientId = id });
97+
dispatcher.Dispatch(new GetClientAction { Id = id });
9898
}
9999

100100
void OnChange(int index)

src/IdServer/SimpleIdServer.IdServer.Website/Pages/Clients.razor

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
</RadzenDataGridColumn>
5858
<RadzenDataGridColumn TItem="SelectableClient" Filterable="false" Sortable="true" SortProperty="Value.ClientId" Title="@Global.Identifier" Width="80px">
5959
<Template Context="data">
60-
<RadzenLink Text="@data.Value.ClientId" Path="@(urlHelper.GetUrl($"/clients/{System.Web.HttpUtility.UrlEncode(data.Value.ClientId)}/settings"))" />
60+
<RadzenLink Text="@data.Value.ClientId" Path="@(urlHelper.GetUrl($"/clients/{data.Value.Id}/settings"))" />
6161
</Template>
6262
</RadzenDataGridColumn>
6363
<RadzenDataGridColumn TItem="SelectableClient" Property="Value.ClientName" Filterable="false" Sortable="false" Title="@Global.Name" Width="80px" />

src/IdServer/SimpleIdServer.IdServer.Website/Stores/ClientStore/ClientEffects.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ public async Task Handle(GetClientAction action, IDispatcher dispatcher)
272272
var httpClient = await _websiteHttpClientFactory.Build();
273273
var requestMessage = new HttpRequestMessage
274274
{
275-
RequestUri = new Uri($"{baseUrl}/{System.Web.HttpUtility.UrlEncode(action.ClientId)}"),
275+
RequestUri = new Uri($"{baseUrl}/bytechnicalid/{action.Id}"),
276276
Method = HttpMethod.Get
277277
};
278278
var httpResult = await httpClient.SendAsync(requestMessage);
@@ -758,7 +758,8 @@ private async Task CreateClient(Domains.Client client, IDispatcher dispatcher, s
758758
try
759759
{
760760
httpResult.EnsureSuccessStatusCode();
761-
dispatcher.Dispatch(new AddClientSuccessAction { ClientId = client.ClientId, ClientName = client.ClientName, Language = client.Translations.FirstOrDefault()?.Language, ClientType = clientType, Pem = pemResult, JsonWebKeyStr = jsonWebKey });
761+
var newClient = JsonSerializer.Deserialize<Client>(json);
762+
dispatcher.Dispatch(new AddClientSuccessAction { Id = newClient.Id, ClientId = client.ClientId, ClientName = client.ClientName, Language = client.Translations.FirstOrDefault()?.Language, ClientType = clientType, Pem = pemResult, JsonWebKeyStr = jsonWebKey });
762763
}
763764
catch
764765
{
@@ -901,6 +902,7 @@ public class AddClientFailureAction
901902

902903
public class AddClientSuccessAction
903904
{
905+
public string Id { get; set; }
904906
public string ClientId { get; set; } = null!;
905907
public string? ClientName { get; set; } = null;
906908
public string? Language { get; set; } = null;
@@ -932,7 +934,7 @@ public class ToggleAllClientSelectionAction
932934

933935
public class GetClientAction
934936
{
935-
public string ClientId { get; set; } = null!;
937+
public string Id { get; set; } = null!;
936938
}
937939

938940
public class GetClientFailureAction

src/IdServer/SimpleIdServer.IdServer.Website/Stores/ClientStore/ClientReducers.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public static SearchClientsState ReduceAddClientSuccessAction(SearchClientsState
3434
{
3535
var clients = state.Clients?.ToList();
3636
if (clients == null) return state;
37-
var newClient = new Domains.Client { ClientId = act.ClientId, CreateDateTime = DateTime.Now, UpdateDateTime = DateTime.Now, ClientType = act.ClientType };
37+
var newClient = new Domains.Client { Id = act.Id, ClientId = act.ClientId, CreateDateTime = DateTime.Now, UpdateDateTime = DateTime.Now, ClientType = act.ClientType };
3838
if(!string.IsNullOrWhiteSpace(act.ClientName))
3939
newClient.Translations.Add(new Translation
4040
{

src/IdServer/SimpleIdServer.IdServer/Api/Clients/ClientsController.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ public async Task<IActionResult> Add([FromRoute] string prefix, [FromBody] Clien
107107
throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(Global.ClientIdentifierAlreadyExists, request.ClientId));
108108
request.Scopes = await GetScopes(prefix, request.Scope, CancellationToken.None);
109109
var realm = await _realmRepository.Get(prefix, cancellationToken);
110+
request.Realms.Clear();
110111
request.Realms.Add(realm);
111112
await _registerClientRequestValidator.Validate(prefix, request, CancellationToken.None);
112113
_clientRepository.Add(request);
@@ -166,6 +167,25 @@ public async Task<IActionResult> Get([FromRoute] string prefix, string id, Cance
166167
}
167168
}
168169

170+
[HttpGet]
171+
public async Task<IActionResult> GetByTechnicalId([FromRoute] string prefix, string id, CancellationToken cancellationToken)
172+
{
173+
prefix = prefix ?? Constants.DefaultRealm;
174+
try
175+
{
176+
id = System.Web.HttpUtility.UrlDecode(id);
177+
await CheckAccessToken(prefix, Constants.StandardScopes.Clients.Name);
178+
var result = await _clientRepository.GetById(prefix, id, cancellationToken);
179+
if (result == null) throw new OAuthException(HttpStatusCode.NotFound, ErrorCodes.NOT_FOUND, string.Format(Global.UnknownClient, id));
180+
return new OkObjectResult(result);
181+
}
182+
catch (OAuthException ex)
183+
{
184+
_logger.LogError(ex.ToString());
185+
return BuildError(ex);
186+
}
187+
}
188+
169189
[HttpDelete]
170190
public async Task<IActionResult> Delete([FromRoute] string prefix, string id, CancellationToken cancellationToken)
171191
{

src/IdServer/SimpleIdServer.IdServer/Stores/IClientRepository.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ namespace SimpleIdServer.IdServer.Stores
1010
{
1111
public interface IClientRepository
1212
{
13+
Task<Client> GetById(string realm, string id, CancellationToken cancellationToken);
1314
Task<Client> GetByClientId(string realm, string clientId, CancellationToken cancellationToken);
1415
Task<List<Client>> GetByClientIds(string realm, List<string> clientIds, CancellationToken cancellationToken);
1516
Task<List<Client>> GetByClientIdsAndExistingBackchannelLogoutUri(string realm, List<string> clientIds, CancellationToken cancellationToken);

src/IdServer/SimpleIdServer.IdServer/WebApplicationExtensions.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,9 @@ public static WebApplication UseSID(this WebApplication webApplication, bool coo
476476
webApplication.SidMapControllerRoute("addClient",
477477
pattern: (usePrefix ? "{prefix}/" : string.Empty) + Constants.EndPoints.Clients,
478478
defaults: new { controller = "Clients", action = "Add" });
479+
webApplication.SidMapControllerRoute("getClientByTechnicalId",
480+
pattern: (usePrefix ? "{prefix}/" : string.Empty) + Constants.EndPoints.Clients + "/bytechnicalid/{id}",
481+
defaults: new { controller = "Clients", action = "GetByTechnicalId" });
479482
webApplication.SidMapControllerRoute("getClient",
480483
pattern: (usePrefix ? "{prefix}/" : string.Empty) + Constants.EndPoints.Clients + "/{id}",
481484
defaults: new { controller = "Clients", action = "Get" });

0 commit comments

Comments
 (0)