Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add crud methods for permissions api #62

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions src/Casdoor.Client/CasdoorClient.CasbinApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using IdentityModel.Client;

namespace Casdoor.Client;

public partial class CasdoorClient
{
public virtual Task<CasdoorResponse<bool>> EnforceAsync(CasdoorEnforceData enforceData, string permissionId, CancellationToken cancellationToken = default) =>
DoEnforceAsync<bool>("enforce", enforceData.ToJsonArray(), permissionId, cancellationToken);

public virtual Task<CasdoorResponse<bool>> BatchEnforceAsync(IEnumerable<CasdoorEnforceData> enforceData, string permissionId, CancellationToken cancellationToken = default) =>
DoEnforceAsync<bool>("batch-enforce", enforceData.ToJsonArray(), permissionId, cancellationToken);

public virtual Task<CasdoorResponse<string>> GetAllObjectsAsync(CancellationToken cancellationToken = default) =>
GetAllAsync<string>("get-all-objects", cancellationToken);

public virtual Task<CasdoorResponse<string>> GetAllActionsAsync(CancellationToken cancellationToken = default) =>
GetAllAsync<string>("get-all-actions", cancellationToken);

public virtual Task<CasdoorResponse<string>> GetAllRolesAsync(CancellationToken cancellationToken = default) =>
GetAllAsync<string>("get-all-roles", cancellationToken);

private async Task<CasdoorResponse<T>> DoEnforceAsync<T>(string url, string data, string permissionId,
CancellationToken cancellationToken = default)
{
var queryMap = new QueryMapBuilder().Add("permissionId", permissionId).QueryMap;
var response = await SendRequestAsync(HttpMethod.Post,
new Uri(_options.GetActionUrl(url, queryMap)),
new StringContent(
data,
Encoding.UTF8,
"application/json"),
cancellationToken);
string responseContent = await response.Content.ReadAsStringAsync(); // netstandard2.0 does not support cancellationToken

if (!response.IsSuccessStatusCode)
{
return new CasdoorResponse<T> { Status = response.StatusCode.ToString(), Msg = responseContent };
}

var deserializedResponse = new CasdoorResponse<T>();
deserializedResponse.DeserializeFromJson(responseContent);
return deserializedResponse;
}

private async Task<CasdoorResponse<T>> GetAllAsync<T>(string url, CancellationToken cancellationToken = default)
{
var response = await SendRequestAsync(HttpMethod.Get, new Uri(_options.GetActionUrl(url)),
cancellationToken: cancellationToken);
string responseContent = await response.Content.ReadAsStringAsync();

if (!response.IsSuccessStatusCode)
{
return new CasdoorResponse<T> { Status = response.StatusCode.ToString(), Msg = responseContent };
}

var deserializedResponse = new CasdoorResponse<T>();
deserializedResponse.DeserializeFromJson(responseContent);
return deserializedResponse;
}

private Task<HttpResponseMessage> SendRequestAsync(HttpMethod method, Uri uri, HttpContent? content = default,
CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage
{
Method = method,
RequestUri = uri,
Content = content
};
request.SetBasicAuthentication(_options.ClientId, _options.ClientSecret);

return _httpClient.SendAsync(request, cancellationToken);
}
}
66 changes: 0 additions & 66 deletions src/Casdoor.Client/CasdoorClient.EnforceApi.cs

This file was deleted.

1 change: 1 addition & 0 deletions src/Casdoor.Client/CasdoorClient.Internal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public partial class CasdoorClient

internal async Task<CasdoorResponse?> PostAsJsonAsync<TValue>(string? requestUri, TValue value, CancellationToken cancellationToken = default)
{
_httpClient.SetCasdoorAuthentication(_options);
HttpResponseMessage resp = await _httpClient.PostAsJsonAsync(requestUri, value, cancellationToken);
return await resp.ToCasdoorResponse(cancellationToken);
}
Expand Down
20 changes: 20 additions & 0 deletions src/Casdoor.Client/CasdoorClient.PermissionApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,26 @@ namespace Casdoor.Client;

public partial class CasdoorClient
{
public virtual async Task<CasdoorResponse?> AddPermissionAsync(CasdoorPermission permission,
CancellationToken cancellationToken = default)
{
string url = _options.GetActionUrl("add-permission");
return await PostAsJsonAsync(url, permission, cancellationToken);
}

public virtual async Task<CasdoorResponse?> UpdatePermissionAsync(CasdoorPermission permission, string permissionId,
CancellationToken cancellationToken = default)
{
string url = _options.GetActionUrl("update-permission", new QueryMapBuilder().Add("id", permissionId).QueryMap);
return await PostAsJsonAsync(url, permission, cancellationToken);
}

public virtual async Task<CasdoorResponse?> DeletePermissionAsync(CasdoorPermission permission, CancellationToken cancellationToken = default)
{
string url = _options.GetActionUrl("delete-permission");
return await PostAsJsonAsync(url, permission, cancellationToken);
}

public virtual async Task<IEnumerable<CasdoorPermission>?> GetPermissionsAsync(CancellationToken cancellationToken = default)
{
var queryMap = new QueryMapBuilder().Add("owner", _options.OrganizationName).QueryMap;
Expand Down
24 changes: 24 additions & 0 deletions src/Casdoor.Client/Extensions/CasdoorEnforceDataExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Casdoor.Client;

public static class CasdoorEnforceDataExtension
{
public static string ToJsonArray(this CasdoorEnforceData enforceData) =>
$"[\"{enforceData.Username}\", \"{enforceData.Resource}\", \"{enforceData.Action}\"]";

public static string ToJsonArray(this IEnumerable<CasdoorEnforceData> enforceData) =>
'[' + string.Join(", ", enforceData.Select(data => data.ToJsonArray())) + ']';
}
34 changes: 34 additions & 0 deletions src/Casdoor.Client/Extensions/CasdoorResponseExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

using System.Text.Json;
using System.Text.Json.Nodes;

namespace Casdoor.Client;

Expand All @@ -31,4 +32,37 @@ public static class CasdoorResponseExtension

return default;
}

internal static void DeserializeFromJson<T>(this CasdoorResponse<T> response, string json)
{
var parsedJson = JsonNode.Parse(json);
response.Status = parsedJson!["status"]!.ToString();
response.Msg = parsedJson["msg"]!.ToString();

if (response.Status != "ok")
{
return;
}

response.Sub = parsedJson["sub"]!.ToString();
response.Name = parsedJson["name"]!.ToString();

try
{
response.Data = parsedJson["data"].Deserialize<IEnumerable<T>>();
}
catch
{
var data = new List<T>();

foreach (var jsonElement in parsedJson["data"].Deserialize<IEnumerable<JsonElement>>()!)
{
data.AddRange(jsonElement.Deserialize<IEnumerable<T>>()!);
}

response.Data = data;
}

response.Data2 = parsedJson["data2"]?.ToString();
}
}
31 changes: 31 additions & 0 deletions src/Casdoor.Client/Models/CasdoorEnforceData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Text.Json.Serialization;

namespace Casdoor.Client;

public class CasdoorEnforceData
{
[JsonPropertyName("username")]
public string? Username { get; set; }

[JsonPropertyName("resource")]
public string? Resource { get; set; }

[JsonPropertyName("action")]
public string? Action { get; set; }
}


32 changes: 0 additions & 32 deletions src/Casdoor.Client/Models/CasdoorPermissionRule.cs

This file was deleted.

4 changes: 1 addition & 3 deletions src/Casdoor.Client/Models/CasdoorResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,12 @@ public class CasdoorResponse
[JsonPropertyName("data2")] public object? Data2 { get; set; }
}


public class CasdoorResponse<T>
{
[JsonPropertyName("status")] public string? Status { get; set; }
[JsonPropertyName("msg")] public string? Msg { get; set; }
[JsonPropertyName("sub")] public string? Sub { get; set; }
[JsonPropertyName("name")] public string? Name { get; set; }
[JsonPropertyName("data")] public T? Data { get; set; }
[JsonPropertyName("data")] public IEnumerable<T>? Data { get; set; }
[JsonPropertyName("data2")] public object? Data2 { get; set; }
}

Loading