Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a5da6ab

Browse files
committed
#优化代码结构#
1 parent 14350a1 commit a5da6ab

File tree

12 files changed

+119
-85
lines changed

12 files changed

+119
-85
lines changed

‎APIJSON.NET/APIJSON.NET/Controllers/JsonController.cs

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,36 @@
22
{
33
using System;
44
using System.Collections.Generic;
5-
using System.Security.Claims;
65
using System.Web;
76
using APIJSON.NET.Models;
87
using Microsoft.AspNetCore.Mvc;
9-
using Microsoft.Extensions.Configuration;
108
using Microsoft.Extensions.Options;
119
using Newtonsoft.Json.Linq;
1210
using SqlSugar;
1311
using System.Linq;
12+
using APIJSON.NET.Services;
1413
[Route("api/[controller]")]
1514
[ApiController]
1615
public class JsonController : ControllerBase
1716
{
1817

19-
private JsonToSqljsonToSql;
18+
private SelectTableselectTable;
2019
private DbContext db;
21-
protectedList<Role>roles;
22-
public JsonController(JsonToSqljsonTo, DbContext _db,IOptions<List<Role>>_roles)
20+
privatereadonlyIIdentityService_identitySvc;
21+
public JsonController(SelectTable_selectTable, DbContext _db,IIdentityServiceidentityService)
2322
{
2423

25-
jsonToSql = jsonTo;
24+
selectTable = _selectTable;
2625
db = _db;
27-
roles = _roles.Value;
26+
_identitySvc = identityService;
2827
}
2928
/// <summary>
3029
/// 查询
3130
/// </summary>
3231
/// <param name="json"></param>
3332
/// <returns></returns>
34-
[HttpPost("/Query")]
35-
public ActionResult Query([FromBody]string json)
33+
[HttpGet("/get/{json}")]
34+
public ActionResult Query(string json)
3635
{
3736
json = HttpUtility.UrlDecode(json);
3837
JObject ht = new JObject();
@@ -44,12 +43,12 @@ public ActionResult Query([FromBody]string json)
4443
foreach (var item in jobject)
4544
{
4645
string key = item.Key.Trim();
46+
var jb = JObject.Parse(item.Value.ToString());
47+
int page = jb["page"] == null ? 0 : int.Parse(jb["page"].ToString()), count = jb["count"] == null ? 0 : int.Parse(jb["count"].ToString()), query = jb["query"] == null ? 0 : int.Parse(jb["query"].ToString());
48+
jb.Remove("page"); jb.Remove("count");
4749
if (key.Equals("[]"))
4850
{
4951
var htt = new JArray();
50-
var jb = JObject.Parse(item.Value.ToString());
51-
int page = jb["page"] == null ? 0 : int.Parse(jb["page"].ToString()), count = jb["count"] == null ? 0 : int.Parse(jb["count"].ToString()) , query = jb["query"] == null ? 0 : int.Parse(jb["query"].ToString());
52-
jb.Remove("page");jb.Remove("count");
5352
List<string> tables = new List<string>(), where = new List<string>();
5453
foreach (var t in jb)
5554
{
@@ -58,32 +57,31 @@ public ActionResult Query([FromBody]string json)
5857
if (tables.Count > 0)
5958
{
6059
string table = tables[0];
61-
var template = jsonToSql.GetTableData(table, page, count, where[0], null,User.FindFirstValue(ClaimTypes.Role));
60+
var template = selectTable.GetTableData(table, page, count, where[0], null);
6261
foreach (var dd in template)
6362
{
6463
var zht = new JObject();
6564
zht.Add(table, JToken.FromObject(dd));
6665
for (int i = 1; i < tables.Count; i++)
6766
{
6867
string subtable = tables[i];
69-
if (tables[i].EndsWith("[]"))
68+
if (subtable.EndsWith("[]"))
7069
{
71-
subtable = tables[i].Replace("[]","");
70+
subtable = subtable.TrimEnd("[]".ToCharArray());
7271
var jbb = JObject.Parse(where[i]);
7372
page = jbb["page"] == null ? 0 : int.Parse(jbb["page"].ToString());
7473
count = jbb["count"] == null ? 0 : int.Parse(jbb["count"].ToString());
7574

7675
var lt = new JArray();
77-
foreach (var d in jsonToSql.GetTableData(subtable, page, count, jbb[subtable].ToString(), zht,User.FindFirstValue(ClaimTypes.Role)))
76+
foreach (var d in selectTable.GetTableData(subtable, page, count, jbb[subtable].ToString(), zht))
7877
{
7978
lt.Add(JToken.FromObject(d));
8079
}
8180
zht.Add(tables[i], lt);
8281
}
8382
else
8483
{
85-
var ddf = jsonToSql.GetTableData(subtable, 0, 0, where[i].ToString(), zht, User.FindFirstValue(ClaimTypes.Role));
86-
84+
var ddf = selectTable.GetTableData(subtable, 0, 0, where[i].ToString(), zht);
8785
if (ddf != null)
8886
{
8987
zht.Add(subtable, JToken.FromObject(ddf));
@@ -98,15 +96,10 @@ public ActionResult Query([FromBody]string json)
9896
}
9997
else if (key.EndsWith("[]"))
10098
{
101-
10299
var htt = new JArray();
103-
var jb = JObject.Parse(item.Value.ToString());
104-
int page = jb["page"] == null ? 0 : int.Parse(jb["page"].ToString()), count = jb["count"] == null ? 0 : int.Parse(jb["count"].ToString());
105-
jb.Remove("page");
106-
jb.Remove("count");
107100
foreach (var t in jb)
108101
{
109-
foreach (var d in jsonToSql.GetTableData(t.Key, page, count, t.Value.ToString(), null,User.FindFirstValue(ClaimTypes.Role)))
102+
foreach (var d in selectTable.GetTableData(t.Key, page, count, t.Value.ToString(), null))
110103
{
111104
htt.Add(JToken.FromObject(d));
112105
}
@@ -115,7 +108,7 @@ public ActionResult Query([FromBody]string json)
115108
}
116109
else
117110
{
118-
var template = jsonToSql.GetTableData(key, 0, 0, item.Value.ToString(), ht,User.FindFirstValue(ClaimTypes.Role));
111+
var template = selectTable.GetTableData(key, 0, 0, item.Value.ToString(), ht);
119112
if (template != null)
120113
{
121114
ht.Add(key, JToken.FromObject(template));
@@ -151,7 +144,7 @@ public ActionResult Add([FromBody]string json)
151144
foreach (var item in jobject)
152145
{
153146
string key = item.Key.Trim();
154-
var role = jsonToSql.GetRole(User.FindFirstValue(ClaimTypes.Role));
147+
var role = _identitySvc.GetRole();
155148
if (!role.Insert.Table.Contains(key, StringComparer.CurrentCultureIgnoreCase))
156149
{
157150
ht["code"] = "500";
@@ -194,7 +187,7 @@ public ActionResult Edit([FromBody]string json)
194187
foreach (var item in jobject)
195188
{
196189
string key = item.Key.Trim();
197-
var role = jsonToSql.GetRole(User.FindFirstValue(ClaimTypes.Role));
190+
var role = _identitySvc.GetRole();
198191
if (!role.Update.Table.Contains(key, StringComparer.CurrentCultureIgnoreCase))
199192
{
200193
ht["code"] = "500";
@@ -244,7 +237,7 @@ public ActionResult Remove([FromBody]string json)
244237
ht.Add("msg", "success");
245238
try
246239
{
247-
var role = jsonToSql.GetRole(User.FindFirstValue(ClaimTypes.Role));
240+
var role = _identitySvc.GetRole();
248241
JObject jobject = JObject.Parse(json);
249242
foreach (var item in jobject)
250243
{

‎APIJSON.NET/APIJSON.NET/Controllers/TokenController.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ public IActionResult Create(string username, string password)
3535
}
3636

3737
var identity = new ClaimsIdentity();
38-
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username));
39-
identity.AddClaim(new Claim(ClaimTypes.Name, username));
38+
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "1"));
39+
identity.AddClaim(new Claim(ClaimTypes.Name, "1"));
4040
identity.AddClaim(new Claim(ClaimTypes.Role, ""));
4141
identity.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, username));
4242
identity.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
File renamed without changes.

‎APIJSON.NET/APIJSON.NET/AuthConfigurer.cs renamed to ‎APIJSON.NET/APIJSON.NET/Infrastructure/AuthConfigurer.cs

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
1-
using Microsoft.AspNetCore.Authentication.JwtBearer;
2-
using Microsoft.Extensions.Configuration;
3-
using Microsoft.Extensions.DependencyInjection;
4-
using Microsoft.IdentityModel.Tokens;
5-
using System;
6-
using System.Collections.Generic;
7-
using System.Linq;
8-
using System.Text;
9-
using System.Threading.Tasks;
10-
namespace APIJSON.NET
1+
namespace APIJSON.NET
112
{
3+
using Microsoft.AspNetCore.Authentication.JwtBearer;
4+
using Microsoft.Extensions.Configuration;
5+
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.IdentityModel.Tokens;
7+
using System;
8+
using System.Linq;
9+
using System.Text;
10+
using System.Threading.Tasks;
1211
public static class AuthConfigurer
1312
{
1413
public static void Configure(IServiceCollection services, IConfiguration configuration)
@@ -19,31 +18,20 @@ public static void Configure(IServiceCollection services, IConfiguration configu
1918
{
2019
sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
2120
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
22-
})
23-
.AddJwtBearer(options =>
21+
}).AddJwtBearer(options =>
2422
{
2523
options.Audience = configuration["Authentication:JwtBearer:Audience"];
26-
2724
options.TokenValidationParameters = new TokenValidationParameters
2825
{
29-
3026
ValidateIssuerSigningKey = true,
3127
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),
32-
3328
ValidateIssuer = true,
3429
ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],
35-
36-
3730
ValidateAudience = true,
3831
ValidAudience = configuration["Authentication:JwtBearer:Audience"],
39-
40-
4132
ValidateLifetime = true,
42-
43-
4433
ClockSkew = TimeSpan.Zero
4534
};
46-
4735
options.Events = new JwtBearerEvents
4836
{
4937
OnMessageReceived = QueryStringTokenResolver,
@@ -52,14 +40,11 @@ public static void Configure(IServiceCollection services, IConfiguration configu
5240
});
5341
}
5442
}
55-
5643
private static Task QueryStringTokenResolver(MessageReceivedContext context)
5744
{
58-
5945
var qsAuthToken = context.Request.Headers["Authorization"].FirstOrDefault();
6046
if (qsAuthToken == null)
6147
{
62-
6348
return Task.CompletedTask;
6449
}
6550
qsAuthToken = qsAuthToken.Replace("Bearer ", "");
File renamed without changes.
File renamed without changes.
File renamed without changes.

‎APIJSON.NET/APIJSON.NET/JsonToSql.cs renamed to ‎APIJSON.NET/APIJSON.NET/SelectTable.cs

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
namespace APIJSON.NET
22
{
33
using APIJSON.NET.Models;
4+
using APIJSON.NET.Services;
45
using Microsoft.Extensions.Options;
56
using Newtonsoft.Json;
67
using Newtonsoft.Json.Linq;
@@ -10,12 +11,14 @@
1011
using System.IO;
1112
using System.Linq;
1213

13-
public class JsonToSql: DbContext
14+
public class SelectTable: DbContext
1415
{
15-
protected List<Role> roles;
16-
public JsonToSql(IOptions<DbOptions> options, IOptions<List<Role>> _roles) : base(options)
16+
17+
private readonly IIdentityService _identitySvc;
18+
public SelectTable(IOptions<DbOptions> options, IIdentityService identityService) : base(options)
1719
{
18-
roles = _roles.Value;
20+
21+
_identitySvc = identityService;
1922
}
2023
/// <summary>
2124
/// 对应数据表
@@ -24,23 +27,10 @@ public JsonToSql(IOptions<DbOptions> options, IOptions<List<Role>> _roles) : bas
2427
{
2528
{"user", "apijson_user"},
2629
};
27-
public Role GetRole(string rolename)
30+
31+
public (bool, string) GetSelectRole(string table)
2832
{
29-
var role = new Role();
30-
if (string.IsNullOrEmpty(rolename))
31-
{
32-
role = roles.FirstOrDefault();
33-
34-
}
35-
else
36-
{
37-
role = roles.FirstOrDefault(it => it.Name.Equals(rolename, StringComparison.CurrentCultureIgnoreCase));
38-
}
39-
return role;
40-
}
41-
public (bool, string) GetSelectRole(string rolename, string table)
42-
{
43-
var role = GetRole(rolename);
33+
var role = _identitySvc.GetRole();
4434
if (role == null || role.Select == null || role.Select.Table == null)
4535
{
4636
return (false, $"select.json权限配置不正确!");
@@ -55,13 +45,13 @@ public Role GetRole(string rolename)
5545
string selectrole = role.Select.Column[index];
5646
return (true, selectrole);
5747
}
58-
public dynamic GetTableData(string subtable, int page, int count, string json, JObject dd,stringrolename)
48+
public dynamic GetTableData(string subtable, int page, int count, string json, JObject dd)
5949
{
6050
if (!subtable.IsTable())
6151
{
6252
throw new Exception($"表名{subtable}不正确!");
6353
}
64-
var role = GetSelectRole(rolename,subtable);
54+
var role = GetSelectRole(subtable);
6555
if (!role.Item1)
6656
{
6757
throw new Exception(role.Item2);
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
using APIJSON.NET.Models;
2+
3+
namespace APIJSON.NET.Services
4+
{
5+
public interface IIdentityService
6+
{
7+
string GetUserIdentity();
8+
string GetUserRoleName();
9+
Role GetRole();
10+
}
11+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using APIJSON.NET.Models;
2+
using Microsoft.AspNetCore.Http;
3+
using Microsoft.Extensions.Options;
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Linq;
7+
using System.Security.Claims;
8+
using System.Threading.Tasks;
9+
10+
namespace APIJSON.NET.Services
11+
{
12+
public class IdentityService : IIdentityService
13+
{
14+
private IHttpContextAccessor _context;
15+
private List<Role> roles;
16+
17+
public IdentityService(IHttpContextAccessor context,IOptions<List<Role>> _roles)
18+
{
19+
_context = context ?? throw new ArgumentNullException(nameof(context));
20+
roles = _roles.Value;
21+
}
22+
public string GetUserIdentity()
23+
{
24+
return _context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
25+
}
26+
27+
public string GetUserRoleName()
28+
{
29+
return _context.HttpContext.User.FindFirstValue(ClaimTypes.Role);
30+
}
31+
public Role GetRole()
32+
{
33+
var role = new Role();
34+
if (string.IsNullOrEmpty(GetUserRoleName()))
35+
{
36+
role = roles.FirstOrDefault();
37+
38+
}
39+
else
40+
{
41+
role = roles.FirstOrDefault(it => it.Name.Equals(GetUserRoleName(), StringComparison.CurrentCultureIgnoreCase));
42+
}
43+
return role;
44+
}
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /