2022-09-02 09:47:41 +08:00
|
|
|
using System;
|
2020-02-18 06:37:48 +08:00
|
|
|
using System.Linq;
|
2020-11-11 03:28:09 +08:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2020-02-04 16:51:15 +08:00
|
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
2020-08-05 15:29:56 +08:00
|
|
|
using SimApi.Communications;
|
|
|
|
|
using SimApi.Exceptions;
|
2020-02-04 16:51:15 +08:00
|
|
|
|
2024-03-23 07:29:43 +08:00
|
|
|
namespace SimApi.Attributes;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 检测登录中间件
|
|
|
|
|
/// </summary>
|
|
|
|
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
|
|
|
|
public class SimApiAuthAttribute : ActionFilterAttribute
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
private string[] Types { get; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
//默认是user登录类型
|
|
|
|
|
public SimApiAuthAttribute()
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
Types = new[] { "user" };
|
|
|
|
|
}
|
2020-02-04 16:51:15 +08:00
|
|
|
|
2024-03-23 07:29:43 +08:00
|
|
|
//只检测一种用户类型的快捷方式
|
|
|
|
|
public SimApiAuthAttribute(string type)
|
|
|
|
|
{
|
|
|
|
|
Types = type.Split(",");
|
|
|
|
|
}
|
2020-11-11 03:28:09 +08:00
|
|
|
|
2024-03-23 07:29:43 +08:00
|
|
|
//设定特定类型的检测
|
|
|
|
|
public SimApiAuthAttribute(string[] types)
|
|
|
|
|
{
|
|
|
|
|
Types = types;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//只检测一种用户类型的快捷方式
|
|
|
|
|
public SimApiAuthAttribute(string type, string url)
|
|
|
|
|
{
|
|
|
|
|
Types = new[] { type };
|
|
|
|
|
new HttpPostAttribute(url);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override void OnActionExecuting(ActionExecutingContext context)
|
|
|
|
|
{
|
|
|
|
|
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"];
|
|
|
|
|
//检测是否登录
|
|
|
|
|
if (loginInfo == null)
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
throw new SimApiException(401);
|
2020-02-04 16:51:15 +08:00
|
|
|
}
|
2024-03-23 07:29:43 +08:00
|
|
|
//检测用户类型
|
|
|
|
|
if (!Types.Intersect(loginInfo.Type).Any())
|
2020-02-04 16:51:15 +08:00
|
|
|
{
|
2024-03-23 07:29:43 +08:00
|
|
|
throw new SimApiException(403);
|
2020-02-04 16:51:15 +08:00
|
|
|
}
|
|
|
|
|
}
|
2022-09-02 09:47:41 +08:00
|
|
|
}
|