Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Prev Previous commit
Next Next commit
#优化代码结构#
  • Loading branch information
liaozb committed Jul 19, 2018
commit a5da6abf612456e9912bfdb11fe8a77f5d46a4a1
49 changes: 21 additions & 28 deletions APIJSON.NET/APIJSON.NET/Controllers/JsonController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,36 @@
{
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Web;
using APIJSON.NET.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Linq;
using APIJSON.NET.Services;
[Route("api/[controller]")]
[ApiController]
public class JsonController : ControllerBase
{

private JsonToSql jsonToSql;
private SelectTable selectTable;
private DbContext db;
protected List<Role> roles;
public JsonController(JsonToSql jsonTo, DbContext _db, IOptions<List<Role>> _roles)
private readonly IIdentityService _identitySvc;
public JsonController(SelectTable _selectTable, DbContext _db,IIdentityService identityService)
{

jsonToSql = jsonTo;
selectTable = _selectTable;
db = _db;
roles = _roles.Value;
_identitySvc = identityService;
}
/// <summary>
/// 查询
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
[HttpPost("/Query")]
public ActionResult Query([FromBody]string json)
[HttpGet("/get/{json}")]
public ActionResult Query(string json)
{
json = HttpUtility.UrlDecode(json);
JObject ht = new JObject();
Expand All @@ -44,12 +43,12 @@ public ActionResult Query([FromBody]string json)
foreach (var item in jobject)
{
string key = item.Key.Trim();
var jb = JObject.Parse(item.Value.ToString());
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());
jb.Remove("page"); jb.Remove("count");
if (key.Equals("[]"))
{
var htt = new JArray();
var jb = JObject.Parse(item.Value.ToString());
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());
jb.Remove("page");jb.Remove("count");
List<string> tables = new List<string>(), where = new List<string>();
foreach (var t in jb)
{
Expand All @@ -58,32 +57,31 @@ public ActionResult Query([FromBody]string json)
if (tables.Count > 0)
{
string table = tables[0];
var template = jsonToSql.GetTableData(table, page, count, where[0], null, User.FindFirstValue(ClaimTypes.Role));
var template = selectTable.GetTableData(table, page, count, where[0], null);
foreach (var dd in template)
{
var zht = new JObject();
zht.Add(table, JToken.FromObject(dd));
for (int i = 1; i < tables.Count; i++)
{
string subtable = tables[i];
if (tables[i].EndsWith("[]"))
if (subtable.EndsWith("[]"))
{
subtable = tables[i].Replace("[]", "");
subtable = subtable.TrimEnd("[]".ToCharArray());
var jbb = JObject.Parse(where[i]);
page = jbb["page"] == null ? 0 : int.Parse(jbb["page"].ToString());
count = jbb["count"] == null ? 0 : int.Parse(jbb["count"].ToString());

var lt = new JArray();
foreach (var d in jsonToSql.GetTableData(subtable, page, count, jbb[subtable].ToString(), zht, User.FindFirstValue(ClaimTypes.Role)))
foreach (var d in selectTable.GetTableData(subtable, page, count, jbb[subtable].ToString(), zht))
{
lt.Add(JToken.FromObject(d));
}
zht.Add(tables[i], lt);
}
else
{
var ddf = jsonToSql.GetTableData(subtable, 0, 0, where[i].ToString(), zht, User.FindFirstValue(ClaimTypes.Role));

var ddf = selectTable.GetTableData(subtable, 0, 0, where[i].ToString(), zht);
if (ddf != null)
{
zht.Add(subtable, JToken.FromObject(ddf));
Expand All @@ -98,15 +96,10 @@ public ActionResult Query([FromBody]string json)
}
else if (key.EndsWith("[]"))
{

var htt = new JArray();
var jb = JObject.Parse(item.Value.ToString());
int page = jb["page"] == null ? 0 : int.Parse(jb["page"].ToString()), count = jb["count"] == null ? 0 : int.Parse(jb["count"].ToString());
jb.Remove("page");
jb.Remove("count");
foreach (var t in jb)
{
foreach (var d in jsonToSql.GetTableData(t.Key, page, count, t.Value.ToString(), null, User.FindFirstValue(ClaimTypes.Role)))
foreach (var d in selectTable.GetTableData(t.Key, page, count, t.Value.ToString(), null))
{
htt.Add(JToken.FromObject(d));
}
Expand All @@ -115,7 +108,7 @@ public ActionResult Query([FromBody]string json)
}
else
{
var template = jsonToSql.GetTableData(key, 0, 0, item.Value.ToString(), ht, User.FindFirstValue(ClaimTypes.Role));
var template = selectTable.GetTableData(key, 0, 0, item.Value.ToString(), ht);
if (template != null)
{
ht.Add(key, JToken.FromObject(template));
Expand Down Expand Up @@ -151,7 +144,7 @@ public ActionResult Add([FromBody]string json)
foreach (var item in jobject)
{
string key = item.Key.Trim();
var role = jsonToSql.GetRole(User.FindFirstValue(ClaimTypes.Role));
var role = _identitySvc.GetRole();
if (!role.Insert.Table.Contains(key, StringComparer.CurrentCultureIgnoreCase))
{
ht["code"] = "500";
Expand Down Expand Up @@ -194,7 +187,7 @@ public ActionResult Edit([FromBody]string json)
foreach (var item in jobject)
{
string key = item.Key.Trim();
var role = jsonToSql.GetRole(User.FindFirstValue(ClaimTypes.Role));
var role = _identitySvc.GetRole();
if (!role.Update.Table.Contains(key, StringComparer.CurrentCultureIgnoreCase))
{
ht["code"] = "500";
Expand Down Expand Up @@ -244,7 +237,7 @@ public ActionResult Remove([FromBody]string json)
ht.Add("msg", "success");
try
{
var role = jsonToSql.GetRole(User.FindFirstValue(ClaimTypes.Role));
var role = _identitySvc.GetRole();
JObject jobject = JObject.Parse(json);
foreach (var item in jobject)
{
Expand Down
4 changes: 2 additions & 2 deletions APIJSON.NET/APIJSON.NET/Controllers/TokenController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ public IActionResult Create(string username, string password)
}

var identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username));
identity.AddClaim(new Claim(ClaimTypes.Name, username));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "1"));
identity.AddClaim(new Claim(ClaimTypes.Name, "1"));
identity.AddClaim(new Claim(ClaimTypes.Role, ""));
identity.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, username));
identity.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APIJSON.NET
namespace APIJSON.NET
{
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class AuthConfigurer
{
public static void Configure(IServiceCollection services, IConfiguration configuration)
Expand All @@ -19,31 +18,20 @@ public static void Configure(IServiceCollection services, IConfiguration configu
{
sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
}).AddJwtBearer(options =>
{
options.Audience = configuration["Authentication:JwtBearer:Audience"];

options.TokenValidationParameters = new TokenValidationParameters
{

ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),

ValidateIssuer = true,
ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],


ValidateAudience = true,
ValidAudience = configuration["Authentication:JwtBearer:Audience"],


ValidateLifetime = true,


ClockSkew = TimeSpan.Zero
};

options.Events = new JwtBearerEvents
{
OnMessageReceived = QueryStringTokenResolver,
Expand All @@ -52,14 +40,11 @@ public static void Configure(IServiceCollection services, IConfiguration configu
});
}
}

private static Task QueryStringTokenResolver(MessageReceivedContext context)
{

var qsAuthToken = context.Request.Headers["Authorization"].FirstOrDefault();
if (qsAuthToken == null)
{

return Task.CompletedTask;
}
qsAuthToken = qsAuthToken.Replace("Bearer ", "");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace APIJSON.NET
{
using APIJSON.NET.Models;
using APIJSON.NET.Services;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Expand All @@ -10,12 +11,14 @@
using System.IO;
using System.Linq;

public class JsonToSql: DbContext
public class SelectTable: DbContext
{
protected List<Role> roles;
public JsonToSql(IOptions<DbOptions> options, IOptions<List<Role>> _roles) : base(options)

private readonly IIdentityService _identitySvc;
public SelectTable(IOptions<DbOptions> options, IIdentityService identityService) : base(options)
{
roles = _roles.Value;

_identitySvc = identityService;
}
/// <summary>
/// 对应数据表
Expand All @@ -24,23 +27,10 @@ public JsonToSql(IOptions<DbOptions> options, IOptions<List<Role>> _roles) : bas
{
{"user", "apijson_user"},
};
public Role GetRole(string rolename)

public (bool, string) GetSelectRole(string table)
{
var role = new Role();
if (string.IsNullOrEmpty(rolename))
{
role = roles.FirstOrDefault();

}
else
{
role = roles.FirstOrDefault(it => it.Name.Equals(rolename, StringComparison.CurrentCultureIgnoreCase));
}
return role;
}
public (bool, string) GetSelectRole(string rolename, string table)
{
var role = GetRole(rolename);
var role = _identitySvc.GetRole();
if (role == null || role.Select == null || role.Select.Table == null)
{
return (false, $"select.json权限配置不正确!");
Expand All @@ -55,13 +45,13 @@ public Role GetRole(string rolename)
string selectrole = role.Select.Column[index];
return (true, selectrole);
}
public dynamic GetTableData(string subtable, int page, int count, string json, JObject dd,string rolename)
public dynamic GetTableData(string subtable, int page, int count, string json, JObject dd)
{
if (!subtable.IsTable())
{
throw new Exception($"表名{subtable}不正确!");
}
var role = GetSelectRole(rolename, subtable);
var role = GetSelectRole(subtable);
if (!role.Item1)
{
throw new Exception(role.Item2);
Expand Down
11 changes: 11 additions & 0 deletions APIJSON.NET/APIJSON.NET/Services/IIdentityService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using APIJSON.NET.Models;

namespace APIJSON.NET.Services
{
public interface IIdentityService
{
string GetUserIdentity();
string GetUserRoleName();
Role GetRole();
}
}
46 changes: 46 additions & 0 deletions APIJSON.NET/APIJSON.NET/Services/IdentityService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using APIJSON.NET.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace APIJSON.NET.Services
{
public class IdentityService : IIdentityService
{
private IHttpContextAccessor _context;
private List<Role> roles;

public IdentityService(IHttpContextAccessor context,IOptions<List<Role>> _roles)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
roles = _roles.Value;
}
public string GetUserIdentity()
{
return _context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
}

public string GetUserRoleName()
{
return _context.HttpContext.User.FindFirstValue(ClaimTypes.Role);
}
public Role GetRole()
{
var role = new Role();
if (string.IsNullOrEmpty(GetUserRoleName()))
{
role = roles.FirstOrDefault();

}
else
{
role = roles.FirstOrDefault(it => it.Name.Equals(GetUserRoleName(), StringComparison.CurrentCultureIgnoreCase));
}
return role;
}
}
}
9 changes: 6 additions & 3 deletions APIJSON.NET/APIJSON.NET/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
using System.Collections.Generic;
using System.Text;
using APIJSON.NET.Models;
using APIJSON.NET.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -50,10 +52,11 @@ public void ConfigureServices(IServiceCollection services)
{
c.SwaggerDoc("v1", new Info { Title = "APIJSON.NET", Version = "v1" });
});
services.AddTransient<DbContext>();
services.AddSingleton<JsonToSql>();
services.AddSingleton<DbContext>();
services.AddSingleton<SelectTable>();
services.AddSingleton<TokenAuthConfiguration>();

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IIdentityService, IdentityService>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down
Loading