Compare commits

...
19 Commits
Author SHA1 Message Date
xrain 6fdb3da059 update minio 2022-05-07 22:56:22 +08:00
xrain 55ea40b757 add string id only 2022-05-07 21:45:12 +08:00
xrain d252c1d302 fix login use string 2022-05-07 21:30:45 +08:00
xrain 74c6cb6027 update to .net6 2021-11-14 15:45:28 +08:00
xrain 98ec9ae231 update to .net6 2021-11-14 15:43:23 +08:00
xrain 18d2dfb86e add get upload url 2021-09-29 02:37:14 +08:00
xrain ef3f1bfa88 fix checkcell regex 2021-09-26 13:11:22 +08:00
xrain 01a2689549 fix ci 2021-07-10 18:39:32 +08:00
xrainandGitHub 916f046789 fix ci 2021-07-10 18:39:02 +08:00
xrain 51ac170a22 add logger 2021-06-28 05:45:29 +08:00
xrain c27011deea add logger 2021-06-28 05:36:54 +08:00
xrain b545af2365 add password oauth method for doc 2021-06-27 10:59:19 +08:00
xrain ac9fd706f9 add map special field method 2021-06-08 10:54:51 +08:00
xrain 8b4d551af8 storage add client 2021-06-07 15:24:22 +08:00
xrain 3445531972 add cors 2021-06-05 14:33:59 +08:00
xrain 2268ad0c8c add cors 2021-06-05 14:30:52 +08:00
xrain 0b6c6af51d add httpcontextaccessor for simapistorage 2021-06-05 12:07:47 +08:00
xrain 1c8ea86fd3 add basemodel 2021-06-05 11:20:32 +08:00
xrain f5e4cc97ba new request type 2021-06-05 07:56:48 +08:00
17 changed files with 315 additions and 76 deletions
-21
View File
@@ -1,21 +0,0 @@
name: PublishNugetPackage
on: [create]
jobs:
publish:
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: '5.0.100'
- name: Publish
run: |
version=`git describe --tags`
dotnet build --configuration release -p:PackageVersion=$version
dotnet nuget push bin/release/Simcu.SimApi.$version.nupkg -k ${NUGET_APIKEY} -s https://www.nuget.org/api/v2/package
env:
NUGET_APIKEY: ${{ secrets.NUGET_APIKEY }}
+24
View File
@@ -0,0 +1,24 @@
name: PublishNugetPackage
on:
push:
tags:
- "*"
jobs:
publish:
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: "6.0.100"
- name: Publish
run: |
version=`git describe --tags`
dotnet build --configuration release -p:PackageVersion=$version
dotnet nuget push bin/release/Simcu.SimApi.$version.nupkg -k ${NUGET_APIKEY} -s https://www.nuget.org/api/v2/package
env:
NUGET_APIKEY: ${{ secrets.NUGET_APIKEY }}
+20 -1
View File
@@ -1,4 +1,5 @@
using System;
namespace SimApi.Communications
{
/// <summary>
@@ -9,12 +10,30 @@ namespace SimApi.Communications
public int Id { get; set; }
}
/// <summary>
/// 只有ID的请求(字符串)
/// </summary>
public class SimApiStringIdOnlyRequest
{
public string Id { get; set; }
}
/// <summary>
/// 动态类型单字段请求
/// </summary>
/// <typeparam name="T"></typeparam>
public class SimApiOneFieldRequest<T>
{
public T Data { get; set; }
}
/// <summary>
/// 基础分页请求
/// </summary>
public class SimApiBasePageRequest
{
public int Page { get; set; }
public int Count { get; set; }
}
}
}
+4 -2
View File
@@ -1,4 +1,5 @@
using System;
namespace SimApi.Communications
{
/// <summary>
@@ -7,8 +8,9 @@ namespace SimApi.Communications
public class SimApiLoginItem
{
//登录用户的ID
public int Id { get; set; }
public string Id { get; set; }
//登录用户来源
public string[] Type { get; set; }
}
}
}
+2
View File
@@ -4,12 +4,14 @@ namespace SimApi.Configs
{
public class SimApiOptions
{
public bool EnableCors { get; set; } = true;
public bool EnableSimApiAuth { get; set; } = false;
public bool EnableSimApiDoc { get; set; } = true;
public bool EnableSimApiException { get; set; } = true;
public bool EnableSimApiStorage { get; set; } = false;
public bool EnableForwardHeaders { get; set; } = true;
public bool EnableLowerUrl { get; set; } = true;
public bool EnableLogger { get; set; } = true;
public SimApiDocOptions SimApiDocOptions { get; set; } = new SimApiDocOptions();
public SimApiStorageOptions SimApiStorageOptions { get; set; } = new SimApiStorageOptions();
-2
View File
@@ -85,7 +85,5 @@ namespace SimApi.Controllers
{
return new SimApiBaseResponse<string>();
}
}
}
+5 -2
View File
@@ -35,10 +35,13 @@ namespace SimApi.Controllers
/// </summary>
/// <returns></returns>
[HttpPost("/auth/check"), SimApiDoc("认证", "检测登陆")]
public SimApiBaseResponse<int> CheckLogin()
public SimApiBaseResponse<string> CheckLogin()
{
ErrorWhenNull(LoginInfo, 401);
return new SimApiBaseResponse<int> {Data = LoginInfo.Id};
return new SimApiBaseResponse<string>
{
Data = LoginInfo.Id
};
}
/// <summary>
+2 -2
View File
@@ -23,7 +23,7 @@ namespace SimApi.Helpers
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public string Login(int id, string type = "user", string token = null)
public string Login(string id, string type = "user", string token = null)
{
return Login(id, new[] { type }, token);
}
@@ -34,7 +34,7 @@ namespace SimApi.Helpers
/// <param name="id"></param>
/// <param name="type"></param>
/// <returns></returns>
public string Login(int id, string[] type, string uuid = null)
public string Login(string id, string[] type, string uuid = null)
{
if (uuid == null)
{
+31 -11
View File
@@ -10,8 +10,13 @@ namespace SimApi.Helpers
public class SimApiStorage
{
private MinioClient Mc { get; }
public MinioClient Client => Mc;
private string ServeUrl { get; }
private string Bucket { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
public SimApiStorage(SimApiOptions apiOptions, IHttpContextAccessor httpContextAccessor)
@@ -19,7 +24,7 @@ namespace SimApi.Helpers
var options = apiOptions.SimApiStorageOptions;
HttpContextAccessor = httpContextAccessor;
var useSsl = false;
var endpoint = string.Empty;
string endpoint;
if (options.Endpoint.StartsWith("http://"))
{
endpoint = options.Endpoint.Replace("http://", string.Empty);
@@ -36,19 +41,33 @@ namespace SimApi.Helpers
ServeUrl = options.ServeUrl;
Bucket = options.Bucket;
Console.WriteLine($"{endpoint} == {options.AccessKey} == {options.SecretKey}");
var mcb = new MinioClient().WithEndpoint(endpoint)
.WithCredentials(options.AccessKey, options.SecretKey);
if (useSsl)
{
Mc = new MinioClient(endpoint, options.AccessKey, options.SecretKey).WithSSL();
}
else
{
Mc = new MinioClient(endpoint, options.AccessKey, options.SecretKey);
mcb = mcb.WithSSL();
}
Mc = mcb.Build();
bool found = Mc.BucketExistsAsync(Bucket).Result;
bool found = Mc.BucketExistsAsync(new BucketExistsArgs().WithBucket(Bucket)).Result;
if (!found)
{
Mc.MakeBucketAsync(Bucket).Wait();
Mc.MakeBucketAsync(new MakeBucketArgs().WithBucket(Bucket)).Wait();
}
}
public string GetUploadUrl(string path, int expire = 7200)
{
try
{
return Mc.PresignedPutObjectAsync(new PresignedPutObjectArgs().WithBucket(Bucket)
.WithObject(path).WithExpiry(expire)).Result;
}
catch (MinioException e)
{
Console.WriteLine("Error occurred: " + e);
return e.Message;
}
}
@@ -56,7 +75,8 @@ namespace SimApi.Helpers
{
try
{
Mc.PutObjectAsync(Bucket, path, stream, stream.Length).Wait();
Mc.PutObjectAsync(new PutObjectArgs().WithBucket(Bucket).WithObject(path).WithStreamData(stream))
.Wait();
return null;
}
catch (MinioException e)
@@ -68,8 +88,8 @@ namespace SimApi.Helpers
public string FullUrl(string path)
{
var httpRequest = HttpContextAccessor.HttpContext.Request;
var url = $"{httpRequest.Scheme}://{httpRequest.Host}";
var httpRequest = HttpContextAccessor.HttpContext?.Request;
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
if (string.IsNullOrEmpty(path))
{
return path;
+2 -10
View File
@@ -1,5 +1,4 @@
using System;
using System.Security.Cryptography;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
@@ -14,7 +13,7 @@ namespace SimApi.Helpers
/// <returns></returns>
public static bool CheckCell(string cell)
{
var regex = new Regex("^1[34578]\\d{9}$");
var regex = new Regex("^1[3456789]\\d{9}$");
return regex.IsMatch(cell);
}
@@ -37,12 +36,5 @@ namespace SimApi.Helpers
return strbul.ToString();
}
public static void Log(string message, string type = "Information")
{
Console.WriteLine($"[ SimApi ][ {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")} ][ {type} ]");
Console.WriteLine(message);
Console.WriteLine("");
}
}
}
+44
View File
@@ -0,0 +1,44 @@
using System;
using Microsoft.Extensions.Logging;
namespace SimApi.Logger
{
public class SimApiLogger : ILogger
{
private string Name { get; }
public SimApiLogger(string name)
{
Name = name;
}
public IDisposable BeginScope<TState>(TState state) => default!;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
{
var defautColor = Console.ForegroundColor;
Console.ForegroundColor = logLevel switch
{
LogLevel.Debug => ConsoleColor.DarkMagenta,
LogLevel.Information => ConsoleColor.DarkCyan,
LogLevel.Warning => ConsoleColor.Yellow,
LogLevel.Error => ConsoleColor.Red,
LogLevel.Critical => ConsoleColor.DarkRed,
_ => defautColor
};
Console.WriteLine(
$"[ {Name} ][ {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")} ][ {logLevel.ToString()} ]");
Console.ForegroundColor = defautColor;
Console.WriteLine($"{state}");
if (exception != null)
{
Console.WriteLine($"{exception}");
}
Console.WriteLine();
}
}
}
+15
View File
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace SimApi.Logger;
public class SimApiLoggerConfiguration
{
public int EventId { get; set; }
public Dictionary<LogLevel, ConsoleColor> LogLevels { get; set; } = new()
{
[LogLevel.Information] = ConsoleColor.Green
};
}
+22
View File
@@ -0,0 +1,22 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
namespace SimApi.Logger
{
public class SimApiLoggerProvider : ILoggerProvider
{
private readonly ConcurrentDictionary<string, SimApiLogger> _loggers =
new ConcurrentDictionary<string, SimApiLogger>();
public ILogger CreateLogger(string categoryName)
{
return _loggers.GetOrAdd(categoryName, name => new SimApiLogger(name));
}
public void Dispose()
{
_loggers.Clear();
}
}
}
+69
View File
@@ -0,0 +1,69 @@
using System;
using System.Linq;
using System.Text.Json;
namespace SimApi.Models
{
public class SimApiBaseModel
{
protected virtual string[] MapperIgnoreField { get; set; } = {"Id", "CreatedAt", "UpdatedAt"};
protected virtual string UpdatedTimeField { get; set; } = "UpdatedAt";
public void MapData<TS>(TS source, bool mapAll = false)
{
//获取要赋值的源数据不为null的项目
var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null)
.Select(x => new {x.Name, x.PropertyType})
.ToDictionary(x => x.Name, x => x.PropertyType);
//获取目标对象的属性信息
var targetProps = GetType().GetProperties().Select(x => new {x.Name, x.PropertyType})
.ToDictionary(x => x.Name, x => x.PropertyType);
foreach (var sp in sourceProps)
{
//检查源对象不为空的属性是否在目标对象中存在
if (targetProps.ContainsKey(sp.Key) && sp.Value == targetProps[sp.Key] &&
(!MapperIgnoreField.Contains(sp.Key) || mapAll))
{
GetType().GetProperty(sp.Key)?
.SetValue(this, source.GetType().GetProperty(sp.Key)?.GetValue(source));
}
}
UpdateTime();
}
public void MapData<TS>(TS source, string[] mapFields)
{
//获取要赋值的源数据不为null的项目
var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null)
.Select(x => new {x.Name, x.PropertyType})
.ToDictionary(x => x.Name, x => x.PropertyType);
//获取目标对象的属性信息
var targetProps = GetType().GetProperties().Select(x => new {x.Name, x.PropertyType})
.ToDictionary(x => x.Name, x => x.PropertyType);
foreach (var sp in sourceProps)
{
//检查源对象不为空的属性是否在目标对象中存在
if (targetProps.ContainsKey(sp.Key) && sp.Value == targetProps[sp.Key] &&
mapFields.Contains(sp.Key))
{
GetType().GetProperty(sp.Key)?
.SetValue(this, source.GetType().GetProperty(sp.Key)?.GetValue(source));
}
}
UpdateTime();
}
/// <summary>
/// 更新update时间
/// </summary>
/// <returns></returns>
public void UpdateTime()
{
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, DateTime.Now);
}
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
"anonymousAuthentication": true
},
"profiles": {
"YYApi": {
"SimApi": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
+4 -5
View File
@@ -14,10 +14,9 @@
<SynchReleaseVersion>false</SynchReleaseVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageVersion>5.0.2</PackageVersion>
<TargetFrameworks>net5.0;netcoreapp3.1</TargetFrameworks>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition=" '$(RunConfiguration)' == 'YYApi' " />
<ItemGroup>
<Folder Include="Helpers\" />
<Folder Include="Communications\" />
@@ -28,9 +27,9 @@
<Folder Include="Configurations\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Minio" Version="3.1.13" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.1.4" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.1.4" />
<PackageReference Include="Minio" Version="4.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.3.1" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.3.1" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>
+70 -19
View File
@@ -5,7 +5,9 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using SimApi.Middlewares;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Logging;
using SimApi.Configs;
using SimApi.Logger;
namespace SimApi
{
@@ -21,12 +23,18 @@ namespace SimApi
var simApiOptions = new SimApiOptions();
options?.Invoke(simApiOptions);
// 是否使用SIMAUTH
// 是否使用 AUTH
if (simApiOptions.EnableSimApiAuth)
{
builder.AddScoped<SimApiAuth>();
}
if (simApiOptions.EnableCors)
{
builder.AddCors(cors => cors.AddPolicy("any",
policy => { policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }));
}
// 使用SimApiDoc
if (simApiOptions.EnableSimApiDoc)
{
@@ -35,7 +43,11 @@ namespace SimApi
{
foreach (var group in docOptions.ApiGroups)
{
x.SwaggerDoc(group.Id, new OpenApiInfo {Title = group.Name, Description = group.Description});
x.SwaggerDoc(group.Id, new OpenApiInfo
{
Title = group.Name,
Description = group.Description
});
}
x.EnableAnnotations();
@@ -53,9 +65,15 @@ namespace SimApi
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{Type = ReferenceType.SecurityScheme, Id = "HeaderToken"}
{
Type = ReferenceType.SecurityScheme,
Id = "HeaderToken"
}
},
new[] {"readAccess", "writeAccess"}
new[]
{
"readAccess", "writeAccess"
}
}
});
haveSimApiAuth = true;
@@ -87,6 +105,14 @@ namespace SimApi
};
haveOauth = true;
break;
case "Password":
oauthFlows.Password = new OpenApiOAuthFlow
{
TokenUrl = new Uri(docOptions.ApiAuth.TokenUrl, UriKind.RelativeOrAbsolute),
Scopes = docOptions.ApiAuth.Scopes
};
haveOauth = true;
break;
}
}
@@ -105,9 +131,15 @@ namespace SimApi
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{Type = ReferenceType.SecurityScheme, Id = "oauth2"}
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
}
},
new[] {"SimApiAuth"}
new[]
{
"SimApiAuth"
}
}
});
}
@@ -115,7 +147,11 @@ namespace SimApi
if (haveSimApiAuth)
{
x.AddSecurityDefinition("HeaderToken",
new OpenApiSecurityScheme {Name = "Token", In = ParameterLocation.Header});
new OpenApiSecurityScheme
{
Name = "Token",
In = ParameterLocation.Header
});
}
});
}
@@ -123,21 +159,22 @@ namespace SimApi
// 使用Header转发,应对代理后获取真实ip
if (simApiOptions.EnableForwardHeaders)
{
builder.Configure<ForwardedHeadersOptions>(options =>
builder.Configure<ForwardedHeadersOptions>(fwOptions =>
{
options.ForwardedHeaders = ForwardedHeaders.All;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
fwOptions.ForwardedHeaders = ForwardedHeaders.All;
fwOptions.KnownNetworks.Clear();
fwOptions.KnownProxies.Clear();
});
}
if (simApiOptions.EnableLowerUrl)
{
builder.AddRouting(options => options.LowercaseUrls = true);
builder.AddRouting(rOptions => rOptions.LowercaseUrls = true);
}
if (simApiOptions.EnableSimApiStorage)
{
builder.AddHttpContextAccessor();
builder.AddSingleton<SimApiStorage>();
}
@@ -152,22 +189,36 @@ namespace SimApi
/// <returns></returns>
public static IApplicationBuilder UseSimApi(this IApplicationBuilder builder)
{
var options = builder.ApplicationServices.GetService<SimApiOptions>();
var options = builder.ApplicationServices.GetRequiredService<SimApiOptions>();
if (options.EnableLogger)
{
builder.ApplicationServices.GetRequiredService<ILoggerFactory>()
.AddProvider(new SimApiLoggerProvider());
}
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiLogger>>();
if (options.EnableForwardHeaders)
{
SimApiUtil.Log("开始配置ForwardedHeaders...");
logger.LogInformation("开始配置ForwardedHeaders...");
builder.UseForwardedHeaders();
}
if (options.EnableCors)
{
logger.LogInformation("开始配置Cors全部允许...");
builder.UseCors("any");
}
if (options.EnableSimApiAuth)
{
SimApiUtil.Log("开始配置SimApiAuth...");
logger.LogInformation("开始配置SimApiAuth...");
builder.UseMiddleware<SimApiAuthMiddleware>();
}
if (options.EnableSimApiDoc)
{
SimApiUtil.Log("开始配置SimApiDoc...");
logger.LogInformation("开始配置SimApiDoc...");
var docOptions = options.SimApiDocOptions;
builder.UseSwagger(x => x.RouteTemplate = "/swagger/{documentName}.json").UseSwaggerUI(x =>
{
@@ -185,20 +236,20 @@ namespace SimApi
if (options.EnableSimApiException)
{
SimApiUtil.Log("开始配置SimApiException...");
logger.LogInformation("开始配置SimApiException...");
builder.UseMiddleware<SimApiExceptionMiddleware>();
}
//请求一下检测存储错误
if (options.EnableSimApiStorage)
{
SimApiUtil.Log("开始配置SimApiStorage...");
logger.LogInformation("开始配置SimApiStorage...");
builder.ApplicationServices.GetService<SimApiStorage>();
}
if (options.EnableLowerUrl)
{
SimApiUtil.Log("开始配置使用URL小写...");
logger.LogInformation("开始配置使用URL小写...");
}
return builder;