Compare commits

...
8 Commits
Author SHA1 Message Date
xrainandGitHub 5a04f831a7 Update main.yml 2020-02-03 03:11:01 +08:00
xrainandGitHub fdfde570c7 Delete publish-nuget.yml 2020-02-03 03:05:58 +08:00
xrainandGitHub 874f5b6cef tag to nuget 2020-02-03 03:05:39 +08:00
xrain 66334d6535 fix: Error without message return wrong message 2020-01-17 20:38:46 +08:00
xrain 608fb26aa2 fix error route 2020-01-17 12:40:22 +08:00
xrain c4e852a0df update 0.1.6 , change checkAuth Attr 2020-01-06 13:08:26 +08:00
xrain d88ee5f50d update version 0.1.5 2020-01-06 12:51:43 +08:00
xrain ad53bb3530 base response add page 2020-01-06 12:50:47 +08:00
12 changed files with 263 additions and 34 deletions
+34
View File
@@ -0,0 +1,34 @@
name: CI
on: [create]
jobs:
build:
name: Build Project
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: '3.1.101'
- name: Build
run: dotnet build MonkeyDotNet/Monkey
publish:
needs: build
name: Publish Project to Nuget
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: '3.1.101'
- name: Publish
run: |
version=`git describe --tags`
dotnet pack --configuration release -p:PackageVersion=$version
dotnet nuget push bin/release/Monkey.$version.nupkg -k ${APIKEY} -s https://www.nuget.org/api/v2/package
env:
APIKEY: ${{ secrets.APPKEY }}
-16
View File
@@ -1,16 +0,0 @@
name: PublishToNuget
on: [push]
jobs:
build:
name: publish to nuget
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 2
- name: Publish NuGet
uses: rohith/publish-nuget@v1.0.3
with:
nuget_key: ${{ secrets.NugetKey }}
+1
View File
@@ -1,6 +1,7 @@
# Created by .ignore support plugin (hsz.mobi) # Created by .ignore support plugin (hsz.mobi)
### C template ### C template
# Prerequisites # Prerequisites
*.sln:
*.d *.d
# Object files # Object files
+22 -3
View File
@@ -25,6 +25,7 @@ namespace YYApi.Communications
private readonly Dictionary<int, string> MsgBox = new Dictionary<int, string>() private readonly Dictionary<int, string> MsgBox = new Dictionary<int, string>()
{ {
{200, "成功"}, {200, "成功"},
{204, "没有数据"},
{400, "参数错误"}, {400, "参数错误"},
{401, "需要登录"}, {401, "需要登录"},
{403, "无权访问"}, {403, "无权访问"},
@@ -94,19 +95,37 @@ namespace YYApi.Communications
{ {
IgnoreReadOnlyProperties = true, IgnoreReadOnlyProperties = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = {new JsonStringEnumConverter()} Converters = { new JsonStringEnumConverter() }
}); });
} }
} }
/// <summary> /// <summary>
/// 动态内容 /// 动态内容分页
/// </summary>
/// <typeparam name="T"></typeparam>
public class BasePageResponse<T> : BaseResponse
{
/// <summary>
/// 动态内容列表
/// </summary>
public T List { get; set; }
//当前页码
public int Page { get; set; }
//每页条数
public int Count { get; set; }
//总计条数
public int Total { get; set; }
}
/// <summary>
/// 动态Data返回
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class BaseResponse<T> : BaseResponse public class BaseResponse<T> : BaseResponse
{ {
/// <summary> /// <summary>
/// 动态内容 /// 动态内容列表
/// </summary> /// </summary>
public T Data { get; set; } public T Data { get; set; }
} }
+18 -2
View File
@@ -46,7 +46,7 @@ namespace YYApi.Controllers
/// <param name="code">错误代码</param> /// <param name="code">错误代码</param>
/// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param> /// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param>
/// <returns></returns> /// <returns></returns>
protected static void Error(int code, string message = null) protected static void Error(int code, string message = "")
{ {
throw new ApiException(code, message); throw new ApiException(code, message);
} }
@@ -57,7 +57,7 @@ namespace YYApi.Controllers
/// <param name="condition">检测条件</param> /// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param> /// <param name="code">错误代码</param>
/// <param name="message">错误描述</param> /// <param name="message">错误描述</param>
protected static void ErrorWhen(bool condition, int code, string message = null) protected static void ErrorWhen(bool condition, int code, string message = "")
{ {
if (condition) if (condition)
{ {
@@ -65,6 +65,17 @@ namespace YYApi.Controllers
} }
} }
/// <summary>
/// 检测给定的变量是否为NUll
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhenNull(object condition, int code, string message = "")
{
ErrorWhen(condition == null, code, message);
}
/// <summary> /// <summary>
/// 错误回馈页面 /// 错误回馈页面
/// </summary> /// </summary>
@@ -78,5 +89,10 @@ namespace YYApi.Controllers
response.SetCode(code); response.SetCode(code);
return response; return response;
} }
protected BaseResponse<string> UploadFile()
{
return new BaseResponse<string>();
}
} }
} }
+3 -2
View File
@@ -47,7 +47,7 @@ namespace YYApi
{ {
return builder.AddSwaggerGen(x => return builder.AddSwaggerGen(x =>
{ {
x.SwaggerDoc("api", new OpenApiInfo {Title = title, Description = description}); x.SwaggerDoc("api", new OpenApiInfo { Title = title, Description = description });
x.EnableAnnotations(); x.EnableAnnotations();
x.AddSecurityRequirement(new OpenApiSecurityRequirement x.AddSecurityRequirement(new OpenApiSecurityRequirement
{ {
@@ -60,10 +60,11 @@ namespace YYApi
} }
}); });
x.AddSecurityDefinition("HeaderToken", x.AddSecurityDefinition("HeaderToken",
new OpenApiSecurityScheme {Name = "Token", In = ParameterLocation.Header}); new OpenApiSecurityScheme { Name = "Token", In = ParameterLocation.Header });
}); });
} }
/// <summary> /// <summary>
/// 使用异常中间价扩展 /// 使用异常中间价扩展
/// </summary> /// </summary>
+31 -3
View File
@@ -1,4 +1,5 @@
using System; using System;
using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
@@ -56,12 +57,39 @@ namespace YYApi.Helpers
/// </summary> /// </summary>
public class CheckAuthAttribute : ActionFilterAttribute public class CheckAuthAttribute : ActionFilterAttribute
{ {
private string[] Types { get; }
//默认是user登录类型
public CheckAuthAttribute()
{
Types = new[] { "user" };
}
//只检测一种用户类型的快捷方式
public CheckAuthAttribute(string type)
{
Types = new[] { type };
}
//设定特定类型的检测
public CheckAuthAttribute(string[] types)
{
Types = types;
}
public override void OnActionExecuting(ActionExecutingContext context) public override void OnActionExecuting(ActionExecutingContext context)
{ {
if (context.HttpContext.Items["LoginId"] == null) var loginInfo = (LoginInfoItem)context.HttpContext.Items["LoginInfo"];
//检测是否登录
if (loginInfo == null)
{ {
throw new ApiException(401); throw new ApiException(401);
} }
//检测用户类型
if (!Types.Contains(loginInfo.Type))
{
throw new ApiException(403);
}
} }
} }
@@ -82,7 +110,7 @@ namespace YYApi.Helpers
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="id"></param>
/// <returns></returns> /// <returns></returns>
public string SetId(int id, string type = "user") public string Set(int id, string type = "user")
{ {
var uuid = GetUUID(); var uuid = GetUUID();
var loginItem = new LoginInfoItem var loginItem = new LoginInfoItem
@@ -99,4 +127,4 @@ namespace YYApi.Helpers
return Guid.NewGuid().ToString(); return Guid.NewGuid().ToString();
} }
} }
} }
+124
View File
@@ -0,0 +1,124 @@
using System;
using Hangfire.Dashboard;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using StackExchange.Redis;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace YYApi.JobService
{
/// <summary>
/// Redis缓存Key定义
/// </summary>
public struct CacheKey
{
public const string HangfireDashboardAuthPrefix = "{hangfire}:dashboard:auth:";
}
/// <summary>
/// HangFire Dashboard Digest认证.
/// </summary>
public class HFDashboardAuth : IDashboardAuthorizationFilter
{
private IConfiguration _config { get; }
private IDatabase _redis { get; }
public HFDashboardAuth(IConfiguration config, IDatabase redis)
{
_redis = redis;
_config = config;
}
public bool Authorize(DashboardContext context)
{
var http = context.GetHttpContext();
if (http.Request.Headers.ContainsKey("Authorization"))
{
var authObj = _processAuthHeader(http.Request.Headers["Authorization"].ToString());
if (http.Request.QueryString.ToString().Contains("logout"))
{
_redis.KeyDelete(CacheKey.HangfireDashboardAuthPrefix + authObj["opaque"]);
_redirect(http);
return true;
}
if (authObj["username"] == _config["Hangfire:User"])
{
var a1 = _md5(string.Format("{0}:Need Login:{1}", authObj["username"], _config["Hangfire:Pass"]));
var a2 = _md5(string.Format("{0}:{1}", http.Request.Method, authObj["uri"]));
var nonce = _redis.StringGet(CacheKey.HangfireDashboardAuthPrefix + authObj["opaque"]);
var validCode = _md5(string.Format("{0}:{1}:{2}:{3}:{4}:{5}", a1, nonce, authObj["nc"], authObj["cnonce"], authObj["qop"], a2));
if (authObj["response"] == validCode)
{
_redis.StringSet(CacheKey.HangfireDashboardAuthPrefix + authObj["opaque"], nonce, new TimeSpan(0, 5, 0));
return true;
}
}
}
_challenge(http);
return false;
}
/// <summary>
/// 生成401认证header
/// </summary>
/// <returns>The challenge.</returns>
private void _challenge(HttpContext http)
{
var response = http.Response;
var guid = Guid.NewGuid().ToString();
var opaque = _md5(guid);
_redis.StringSet(CacheKey.HangfireDashboardAuthPrefix + opaque, guid, new TimeSpan(0, 0, 30));
response.StatusCode = 401;
response.Headers.Add("WWW-Authenticate", string.Format("Digest realm=\"Need Login\",qop=\"auth\",nonce=\"{0}\",opaque=\"{1}\"", guid, opaque));
}
/// <summary>
/// 跳转到页面不附加参数
/// </summary>
/// <param name="http">Http.</param>
private void _redirect(HttpContext http)
{
var response = http.Response;
response.StatusCode = 302;
response.Headers.Add("Location", (http.Request.PathBase + http.Request.Path).ToString());
}
/// <summary>
/// 处理DigestHeader中的参数为字典
/// </summary>
/// <returns>The auth header.</returns>
/// <param name="authData">Auth data.</param>
private Dictionary<string, string> _processAuthHeader(string authData)
{
var authDataArray = authData.Replace("Digest ", string.Empty).Replace("\"", string.Empty).Split(", ");
var authDic = new Dictionary<string, string>();
foreach (var item in authDataArray)
{
var tmp = item.Split("=", 2);
authDic.Add(tmp[0], tmp[1]);
}
return authDic;
}
/// <summary>
/// 计算字符串32位MD5
/// </summary>
/// <returns>The md5.</returns>
/// <param name="source">Source.</param>
private string _md5(string source)
{
byte[] sor = Encoding.UTF8.GetBytes(source);
var md5 = MD5.Create();
byte[] result = md5.ComputeHash(sor);
StringBuilder strbul = new StringBuilder(40);
for (int i = 0; i < result.Length; i++)
{
strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
}
return strbul.ToString();
}
}
}
+10
View File
@@ -0,0 +1,10 @@
using System;
namespace YYApi.JobService
{
public class JobDashboardConfig
{
public string Path { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
+10
View File
@@ -0,0 +1,10 @@
using System;
namespace YYApi.JobService
{
public class JobStorage
{
public JobStorage()
{
}
}
}
+2 -2
View File
@@ -15,7 +15,7 @@ namespace Controllers
/// <summary> /// <summary>
/// 获取登录用户信息 /// 获取登录用户信息
/// </summary> /// </summary>
protected User LoginInfo => (User) HttpContext.Items["LoginInfo"]; protected LoginInfoItem LoginInfo => (LoginInfoItem) HttpContext.Items["LoginInfo"];
} }
} }
``` ```
@@ -40,7 +40,7 @@ namespace Controllers
#Startup.cs #Startup.cs
service.AddAuth(); service.AddAuth();
``` ```
添加时候, 可以从DI中获取 Auth 类,调用 Auth.SetId(int) 将用户ID和生成的Token绑定,本方法返回缓存中的Key名称 添加时候, 可以从DI中获取 Auth 类,调用 Auth.Set(int,string) 将用户ID/类型和生成的Token绑定,本方法返回缓存中的Key名称
```C# ```C#
#Startup.cs #Startup.cs
+8 -6
View File
@@ -4,7 +4,7 @@
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.1</TargetFramework>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<PackOnBuild>true</PackOnBuild> <PackOnBuild>true</PackOnBuild>
<Version>0.1.3</Version> <Version>0.2.1</Version>
<Authors>xRain@YYTech</Authors> <Authors>xRain@YYTech</Authors>
<Description>AspNetCore一个方便的API文档,捕获异常,统一输入输出的API类库</Description> <Description>AspNetCore一个方便的API文档,捕获异常,统一输入输出的API类库</Description>
<PackageId>YY-Tech.YYApi</PackageId> <PackageId>YY-Tech.YYApi</PackageId>
@@ -17,13 +17,15 @@
<Folder Include="Helpers\" /> <Folder Include="Helpers\" />
<Folder Include="Communications\" /> <Folder Include="Communications\" />
<Folder Include="Controllers\" /> <Folder Include="Controllers\" />
<Folder Include="JobService\" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Remove="Properties\launchSettings.json" /> <PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="5.0.0" />
</ItemGroup> <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0" />
<ItemGroup> <PackageReference Include="HangFire.Core" Version="1.7.8" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="5.0.0-rc5" /> <PackageReference Include="Hangfire.AspNetCore" Version="1.7.8" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0-rc5" /> <PackageReference Include="Hangfire.Console" Version="1.4.2" />
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.8.1" />
</ItemGroup> </ItemGroup>
<ProjectExtensions> <ProjectExtensions>
<MonoDevelop> <MonoDevelop>